是否有与TypeScript兼容的方式来使用Sequelize访问关联的实体?

时间:2018-03-18 16:09:57

标签: typescript model associations sequelize.js

我正在开发一个运行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环境中是否还有其他方法可以访问关联实体及其属性?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

Sequelize会在运行时将getOtherModels等方法添加到对象中,因此您只需告诉Typescript它们将在运行时存在于MyModel个实例上,以便您可以使用它们:

export interface MyInstance extends Sequelize.Instance<MyAttribute>, MyAttribute { 
    getOtherModels(): Promise<OtherModel[]>
}