不工作的代码只是为了说明我想要实现的目标
一些连接文件
import { ConnectionManager } from 'typeorm';
const c = new ConnectionManager();
// user ormconfig.conf file
export const connection = c.createAndConnect();
在某些模型中使用
@Entity()
@Table("annual_incomes")
export class AnnualIncome
{
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 75 })
variant: string;
@Column("int")
sort: number;
@Column()
is_active: boolean;
}
后来在代码中的某个地方,我想与所有方法建立连接,例如:
import { connection } from 'someconnection';
import { AnnualIncome } from 'entities';
// some code here
api.get('/incomes', async(ctx) => {
ctx.body = await connection.getRepository(AnnualIncome).find();
});
通常,我会收到错误tsc
that .getRepository()
没有找到方法connection
。但是,如果我做类似的事情:
import { connection } from 'someconnection';
import { AnnualIncome } from 'entities';
// some code here
api.get('/incomes', async(ctx) => {
ctx.body = await connection.then(async connection => {
return await connection.getRepository(AnnualIncome).find();
}
});
上面的代码适用于定义和tsc
不会抱怨不存在的方法。
我想避免额外的定义connection.then()
并变得简单connection
与定义的所有方法<Connection>
type.