TypeScript中如何配置Sequelize模型,使create、build调用时字段可选
修改步骤
- 首先在你的用户模型文件中新增创建属性类型定义,把自动生成不需要手动传入的字段标记为可选:
// 从sequelize导入Optional工具类型 import { BuildOptions, DataTypes, Model, Sequelize, Optional } from "sequelize"; import { IDBUserAttributes } from "./shared/db-table"; // 新增:定义创建User时的入参类型,排除自动生成的id、createdAt、updatedAt interface UserCreationAttributes extends Optional<IDBUserAttributes, "id" | "createdAt" | "updatedAt"> {}
- 调整Model的泛型参数,将第二个泛型(创建实例的入参类型)替换为上面定义的
UserCreationAttributes:
interface UserModel extends Model<IDBUserAttributes, UserCreationAttributes>, IDBUserAttributes {} // 此处第二个泛型从原来的IDBUserAttributes改为UserCreationAttributes class User extends Model<UserModel, UserCreationAttributes> {}
- 修正
UserStatic构造函数的参数类型,匹配创建属性规则:
type UserStatic = typeof Model & { new (values?: UserCreationAttributes, options?: BuildOptions): UserModel; };
其余的UserFactory逻辑、导出内容不需要修改。
完整修改后的模型代码
import { BuildOptions, DataTypes, Model, Sequelize, Optional } from "sequelize"; import { IDBUserAttributes } from "./shared/db-table"; // 新增创建时的属性类型 interface UserCreationAttributes extends Optional<IDBUserAttributes, "id" | "createdAt" | "updatedAt"> {} interface UserModel extends Model<IDBUserAttributes, UserCreationAttributes>, IDBUserAttributes {} // 替换第二个泛型为创建属性类型 class User extends Model<UserModel, UserCreationAttributes> {} type UserStatic = typeof Model & { new (values?: UserCreationAttributes, options?: BuildOptions): UserModel; }; const UserFactory = (sequelize: Sequelize): UserStatic => { return <UserStatic>sequelize.define("users", { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, unique: true, }, 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, defaultValue: DataTypes.NOW, }, updatedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, }, }); } export { UserModel, User, UserFactory, UserStatic, }
修改完成后,调用User.create()或者User.build()时仅需传入email、username、password三个必填字段即可,不会再触发类型报错。
内容的提问来源于stack exchange,提问作者user16657995
相关产品推荐
相关产品推荐

