问题描述
我正在使用打字稿和打字稿。我有这个实体:
import { Entity,Column,PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Sample {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 50 })
name: string;
@Column('text',{ nullable: true })
description: string;
}
我查询这样的单个结果:
const connection = await this.getConnection();
const sampleRepo = await connection.getRepository(Sample);
const sample = await sampleRepo.createQueryBuilder('sample')
.where('sample.id = :id',{ id: id })
.getOne();
现在,我需要对结果列进行一些处理,但示例对象的类型为EntitySchema
。因此,在打字稿中,我无法执行sample.id
,因为错误:
Property 'id' does not exist on type 'EntitySchema<any>'
反正有将EntitySchema
转换为实际的Sample
对象吗?
解决方法
事实证明,这是由于执行不当所致。我将存储库的创建移到了一个单独的类中:
export default class Database {
private connectionManager: ConnectionManager
constructor() {
this.connectionManager = getConnectionManager();
}
public getRepository<T extends EntitySchema>(type: ObjectType<T> | EntitySchema<T> | string): Promise<Repository<T>> {
const connection = await this.getConnection();
return connection.getRepository(type);
}
public async getConnection(connectionName = 'default'): Promise<Connection> {
let connection: Connection;
if (this.connectionManager.has(connectionName)) {
connection = this.connectionManager.get(connectionName);
if (!connection.isConnected) {
connection = await connection.connect();
}
}
else {
const connectionOptions: ConnectionOptions = Object
.assign({ name: connection },connectionProperties);
connection = await createConnection(connectionOptions);
}
return connection;
}
}
connection.getRepository
似乎没有返回承诺。同样,T
泛型不应该扩展EntitySchema
。为了使功能按预期工作,我必须这样写:
public getRepository<T>(type: ObjectType<T> | EntitySchema<T> | string): Promise<Repository<T>> {
return new Promise((resolve,reject) => {
this.getConnection().then(conn => {
resolve(conn.getRepository(type));
}).catch(reject);
});
}