这是我的模型-
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
import { IDBUserAttributes } from "./shared/db-table";
interface UserModel extends Model<IDBUserAttributes>, IDBUserAttributes {}
class User extends Model<UserModel, IDBUserAttributes> {}
type UserStatic = typeof Model & {
new (values?: object, 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,
}
IDBUserAttributes
获得了所有用于类型检查的字段。
这是index.ts
文件-
import { UserFactory } from '../user';
import { MovieFactory } from '../movie';
import { FavoriteMoviesFactory } from '../favoriteMovies';
import * as sequelize from "sequelize";
const instantiateObj = {
database: process.env.MYSQL_DB_NAME,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PWD,
port: process.env.MYSQL_PORT,
host: process.env.MYSQL_HOST,
}
const dbConfig = new sequelize.Sequelize(instantiateObj.database, instantiateObj.username, instantiateObj.password, {
port: Number(instantiateObj.port),
host: instantiateObj.host,
dialect: "mysql",
pool: {
min: 0,
max: 5,
acquire: 30000,
idle: 10000,
},
}
);
const User = UserFactory(dbConfig);
const Movie = MovieFactory(dbConfig);
const FavoriteMovies = FavoriteMoviesFactory(dbConfig);
export {
dbConfig,
User,
Movie,
FavoriteMovies,
}
我想使用没有所有字段的User.create() or User.build()
。现在我不能这样做,因为IDBUserAttributes
我得到错误-
Argument of type '{ email: string; username: string; password: string; }' is not assignable to parameter of type 'IDBUserAttributes'.
Type '{ email: string; username: string; password: string; }' is missing the following properties from type 'IDBUserAttributes': id, createdAt, updatedAtts(2345)
我去了- https://sequelize.org/master/manual/typescript.html#usage-of--code-sequelize-define--code-
看到-
//当调用UserModel.create()或UserModel.build()时,有些字段是可选的
interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}
我如何将其应用到我的代码中?
您可以使用联合指定可选字段:
interface IDBUserCreationAttributes extends Optional<IDBUserAttributes, "id" | "createdAt" | "updatedAt"> {}
class User extends Model<IDBUserAttributes, IDBUserCreationAttributes> {}