TypeScript中Sequelize调用create方法属性类型不匹配如何解决?
根因
IDBUserAttributes将数据库自动生成的id、createdAt、updatedAt字段设为必填项,Sequelize的Model泛型第二个参数为创建实例时允许传入的属性类型,当前传入全量的IDBUserAttributes,导致create方法调用时TS校验要求必须传入三个自动生成字段,触发类型错误。
解决方案
核心是拆分「全量属性接口」和「创建时可传入属性接口」,将自动生成字段从创建参数的必填校验中排除:
- 先调整基础类型定义,新增通用的创建属性工具类型:
// 基础全量属性接口(修正拼写错误,原定义IDBAtribute少了字符t) interface IDBAttribute { readonly id: number; readonly createdAt: Date; readonly updatedAt: Date; } // 通用创建属性类型:自动排除三个自动生成的字段 type IDBCreationAttr<T extends IDBAttribute> = Omit<T, 'id' | 'createdAt' | 'updatedAt'> // 用户属性接口(修正笔误,原定义误写为IDBMoviesAttributes) interface IDBUserAttributes extends IDBAttribute { readonly email: string; readonly username: string; readonly password: string; }
- 修改User模型的泛型参数和类型定义:
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize"; import { IDBUserAttributes, IDBCreationAttr } from "./shared/db-table"; // 定义创建用户时的入参类型 type IDBUserCreationAttributes = IDBCreationAttr<IDBUserAttributes> interface UserModel extends Model<IDBUserAttributes, IDBUserCreationAttributes>, IDBUserAttributes {} type UserStatic = typeof Model & { new (values?: Partial<IDBUserAttributes>, options?: BuildOptions): UserModel; }; const UserFactory = (sequelize: Sequelize): UserStatic => { return <UserStatic>sequelize.define("users", { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, unique: true, allowNull: false, }, email: { type: DataTypes.STRING(320), allowNull: false, unique: true, }, username: { type: DataTypes.STRING(26), allowNull: false, }, password: { type: DataTypes.STRING(255), allowNull: false, }, createdAt: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW, }, updatedAt: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW, }, }); } export { UserModel, UserFactory, UserStatic, IDBUserCreationAttributes }
修改完成后调用User.create传入email、username、password三个字段即可通过TS类型校验,自动生成的三个字段不会再要求手动传入。
内容的提问来源于stack exchange,提问作者user16657995
相关产品推荐
相关产品推荐

