TypeScript & Sequelize: Pass in generic Model

落爺英雄遲暮 提交于 2019-12-11 06:35:17

问题


I have this code

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);

The console.log statement returns:

// [ { name: 'Users' } ]

So I know the code works, however, TypeScript complains that:

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

on the model.init(...) call.

I think TS thinks I'm passing in a Model object directory. I guess I need to tell it it's a type of Model, or the object passed in was extended from it. How do I tell TypeScript that the argument model: Model is valid? I tried to use model: Model<T> and `model: T any other variations, but to no avail.


回答1:


You should create a static type representation of your models like:

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

And you could define the InitAndDefineModel function like this:

function async InitAndDefineModel(model: ModelStatic): void

In such a case the model passed to above function should now allow to access static methods of Sequelize.Model



来源:https://stackoverflow.com/questions/57129544/typescript-sequelize-pass-in-generic-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!