node.js - 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,所以我找不到这样的例子。任何帮助表示赞赏。
解决方案
从手册
从 v5 开始,Sequelize 提供了自己的 TypeScript 定义。请注意,仅支持 TS >= 3.1。
由于 Sequelize 严重依赖运行时属性分配,TypeScript 开箱即用并不是很有用。需要大量的手动类型声明才能使模型可行。
您可以在文档底部找到sequelize.define
with的用法。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');
})();
推荐阅读
- r - 相关矩阵和分类变量
- python - ValueError: list.remove(x): x not in list 当我尝试从列表中删除元素时
- javascript - 防止在 ::before 伪元素下出现换行符
- python - 熊猫数据框如何制作散点图以将值列表聚类到一组组中
- azure - 在 IIS 上运行 FastAPI 应用程序时出现网关错误
- git - 为什么我的文件从本地推送后没有出现在 Github 中?
- amazon-ecs - 运行 pgadminin ecs 时运行状况检查请求超时
- javascript - ajax json表格分组行
- python - Python - 特定网页上的 WebDriverException 问题
- google-bigquery - 使用 Cloud Functions 将 Pub/Sub 消息发送到 BigQuery 的有效方式