首页 > 解决方案 > sequelize.define() 在 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。使用“any”会破坏目的。我怎么知道我的模型应该使用哪种类型?不幸的是,大多数 sequelize 的文档都是普通的 javascript,所以我找不到这样的例子。任何帮助表示赞赏。

标签: node.jstypescriptsequelize.js

解决方案


手册

从 v5 开始,Sequelize 提供了自己的 TypeScript 定义。请注意,仅支持 TS >= 3.1。

由于 Sequelize 严重依赖运行时属性分配,TypeScript 开箱即用并不是很有用。需要大量的手动类型声明才能使模型可行。

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

例如"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');
})();

推荐阅读