gpt4 book ai didi

node.js - sequelize.define() 在 TypeScript 中返回什么类型?

转载 作者:行者123 更新时间:2023-12-03 22:19:17 26 4
gpt4 key购买 nike

所以我最终决定尝试 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,所以我找不到这样的例子。任何帮助表示赞赏。

最佳答案

来自 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.define的用法与 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');
})();

关于node.js - sequelize.define() 在 TypeScript 中返回什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64207295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com