sequelize.define() return 在 TypeScript 中是什么类型?

What Type does sequelize.define() return in TypeScript?

所以我最终决定尝试使用 TypeScript,因为我听说过它的一切以及静态类型对我有好处。我决定通过使用 sequelize 创建一个简单的 Web API 来测试它,但我无法理解从 sequelize 返回的类型。所以我有以下导入(请注意,我还安装了 @types/sequelize npm 模块:

import sequelize = require('sequelize');
import  {DataTypes} from 'sequelize';

我正在这样创建我的模型:

    const User:sequelize.Model= db.define('User',{
        id: {type:DataTypes.INTEGER, primaryKey:true},
        email:{type:DataTypes.STRING, allowNull:false},
        hashedPassword:{type:DataTypes.STRING,allowNull:false}
    });

但是我收到这个错误:

Type 'ModelCtor<Model<any, any>>' is missing the following properties from type 'Model<any,any>': _attributes, _creationAttributes, isNewRecord, where, and 16 more.

但是如果我这样做:

const User:any= db.define('User',{
    id: {type:DataTypes.INTEGER, primaryKey:true},
    email:{type:DataTypes.STRING, allowNull:false},
    hashedPassword:{type:DataTypes.STRING,allowNull:false}
});

它工作正常。但当然,因为这是 TypeScript,我想利用 Types。使用“任何”都违背了目的。我怎么知道应该为我的模型使用哪种类型?不幸的是,大多数 sequelize 的文档都是常规的 javascript,所以我找不到这方面的例子。感谢任何帮助。

来自manual

Since v5, Sequelize provides its own TypeScript definitions. Please note that only TS >= 3.1 is supported.

As Sequelize heavily relies on runtime property assignments, TypeScript won't be very useful out of the box. A decent amount of manual type declarations are needed to make models workable.

您可以在文档底部找到 sequelize.defineTypeScript 的用法。

例如"sequelize": "^5.21.3"

user.ts:

import { Sequelize, DataTypes, Model, BuildOptions } from 'sequelize';

const db = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

interface UserAttributes {
  readonly id: number;
  readonly email: string;
  readonly hashedPassword: string;
}
interface UserInstance extends Model<UserAttributes>, UserAttributes {}
type UserModelStatic = typeof Model & {
  new (values?: object, options?: BuildOptions): UserInstance;
};

const User = db.define('User', {
  id: { type: DataTypes.INTEGER, primaryKey: true },
  email: { type: DataTypes.STRING, allowNull: false },
  hashedPassword: { type: DataTypes.STRING, allowNull: false },
}) as UserModelStatic;

(async function test() {
  const user: UserInstance = await User.create({
    id: 1,
    hashedPassword: '123',
    email: 'test@gmail.com',
  });
  user.getDataValue('email');
})();