【问题标题】:TypeScript & Sequelize: Pass in generic ModelTypeScript & Sequelize:传入泛型模型
【发布时间】:2019-11-29 10:58:02
【问题描述】:

我有这个代码

import { Model, DataTypes, Sequelize } from "sequelize";

class User extends Model {
    public id!: number;
    public firstName!: string;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
}

function async InitAndDefineModel(model: Model): void {
    const sequelize = new Sequelize({
        dialect: "sqlite",
        storage: ":memory:",
    });
    model.init{
        firstName: {
            allowNull: false,
            type: DataTypes.STRING,
        },
    },
    {
        sequelize,
    });
    const tables = await sequelize.showAllSchemas({});
    console.log(tables);
}

InitAndDefineModel(User);

console.log 语句返回:

// [ { name: 'Users' } ]

所以我知道代码有效,但是 TypeScript 抱怨说:

Property 'init' is a static member of type 'Model<any, any>'ts(2576)

model.init(...) 通话中。

我认为 TS 认为我正在传递一个模型对象目录。我想我需要告诉它它是一种模型,或者传入的对象是从它扩展而来的。 如何告诉 TypeScript 参数 model: Model 是有效的?我尝试使用 model: Model&lt;T&gt; 和 `model: T 任何其他变体,但无济于事。

【问题讨论】:

    标签: typescript sequelize.js typescript-generics


    【解决方案1】:

    您应该创建模型的静态类型表示,例如:

    type ModelStatic = typeof Model & {
      new(values?: object, options?: Sequelize.BuildOptions): Model;
    }
    

    您可以像这样定义InitAndDefineModel 函数:

    function async InitAndDefineModel(model: ModelStatic): void
    

    在这种情况下,传递给上述函数的model 现在应该允许访问Sequelize.Model 的静态方法

    【讨论】:

    • 我不得不稍微调整您的类型定义以满足 TS lint 规则:type ModelStatic = typeof Model &amp; (new(values?: object, options?: BuildOptions) =&gt; Model);。除此之外,它还有效。谢谢。
    • export abstract class EntityService&lt;Entity&gt; { readonly entity; async findById(id: number): Promise&lt;Entity&gt; { const model = await this.entity.findByPk(id) if (model) return model throw new NotFoundException() } } 您好,您能帮忙解决一下上述问题吗?如何在 EntityService 类中设置属性 entity 的类型,以便我可以在 findById 函数中获得智能感知功能?
    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 2019-09-28
    • 2020-11-05
    • 1970-01-01
    • 2019-05-30
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多