【问题标题】:What Type does sequelize.define() return in TypeScript?sequelize.define() 在 TypeScript 中返回什么类型?
【发布时间】:2021-01-20 05:46:52
【问题描述】:

所以我最终决定尝试 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.js typescript sequelize.js


    【解决方案1】:

    来自manual

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

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

    您可以在文档底部找到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');
    })();
    

    【讨论】:

    • 你能解释一下这行是怎么回事吗:interface UserInstance extends Model, UserAttributes {} 据我所知,TypeScript 不支持多重继承。 , 在这里做什么?
    • @tutiplain 这是一个接口,而不是一个类。一个接口可以在 TypeScript 中扩展多个接口。
    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 2020-02-11
    • 2018-12-05
    • 2019-08-21
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多