打字稿Sequelize:传入通用模型 [英] TypeScript & Sequelize: Pass in generic Model
问题描述
我有这个代码
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 语句返回:
The console.log statement returns:
// [ { name: 'Users' } ]
所以我知道代码有效,但是 TypeScript 抱怨说:
So I know the code works, however, TypeScript complains that:
Property 'init' is a static member of type 'Model<any, any>'ts(2576)
在 model.init(...)
调用上.
我认为 TS 认为我正在传递一个模型对象目录.我想我需要告诉它它是一种模型,或者传入的对象是从它扩展而来的.如何告诉 TypeScript 参数 model: Model
是有效的?我尝试使用 model: Model<T>
和 `model: T 任何其他变体,但无济于事.
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.
推荐答案
您应该为您的模型创建一个静态类型表示,例如:
You should create a static type representation of your models like:
type ModelStatic = typeof Model & {
new(values?: object, options?: Sequelize.BuildOptions): Model;
}
您可以像这样定义 InitAndDefineModel
函数:
And you could define the InitAndDefineModel
function like this:
function async InitAndDefineModel(model: ModelStatic): void
在这种情况下,传递给上述函数的 model
现在应该允许访问 Sequelize.Model
In such a case the model
passed to above function should now allow to access static methods of Sequelize.Model
这篇关于打字稿Sequelize:传入通用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!