我正在开发一个运行Sequelize的TypeScript应用程序。这是一个最小的示例模型:
import * as Sequelize from 'sequelize';
export interface MyAttribute {
id: number,
descr: string
}
export interface MyInstance extends Sequelize.Instance<MyAttribute>, MyAttribute { }
export interface MyModel extends Sequelize.Model<MyInstance, MyAttribute> { }
export default class MyManager {
//[...]
constructor() {
this.model = this.sequelize.define<MyInstance, MyAttribute>("MyEntity", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
descr: {
type: Sequelize.INTEGER
}
});
}
public initRelations() {
this.model.belongsTo(OtherModel.model);
this.model.sync({force:true});
}
}
现在我想通过MyInstance对象访问OtherModel的关联实体。我尝试了 getOtherModels(),但这在TypeScript编译期间无效。在此TypeScript环境中是否还有其他方法可以访问关联实体及其属性?
感谢您的帮助。
答案 0 :(得分:1)
Sequelize会在运行时将getOtherModels
等方法添加到对象中,因此您只需告诉Typescript它们将在运行时存在于MyModel
个实例上,以便您可以使用它们:
export interface MyInstance extends Sequelize.Instance<MyAttribute>, MyAttribute {
getOtherModels(): Promise<OtherModel[]>
}