![](/img/trans.png)
[英]Sequelize / Typescript: Types of parameters 'values' and 'values' are incompatible
[英]Is there a way to use types from a sequelize model in typescript?
有没有办法将我的类型从续集模型传递到打字稿?
我的型号代码:
import { Table, Column, Model, DataType } from 'sequelize-typescript';
@Table
export class User extends Model {
@Column({ type: DataType.UUID, defaultValue: DataType.UUIDV4 })
userId!: string;
@Column({ allowNull: false })
username!: string;
@Column({ allowNull: false, unique: true })
email!: string;
@Column({ defaultValue: false })
confirmed!: boolean;
@Column({ allowNull: false })
password!: string;
@Column({ defaultValue: false })
isAdmin!: boolean;
}
我的路线中带有模型实例字段的代码,它们都具有任何类型:
const { userId, username, email, confirmed, password, isAdmin } = req.body;
是的,您可以使用User
类作为req.body
的类型。
const {
userId,
username,
email,
confirmed,
password,
isAdmin
} = req.body as User
您应该对User
类型有点小心,因为它包含许多额外的函数,如$count()
或$create()
。 在使用它来键入用户输入时,您应该将它们从类型中排除。
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>
const {
userId,
username,
email,
confirmed,
password,
isAdmin
} = req.body as NonFunctionProperties<User>
如果您只想要在User
类中定义的属性而不需要从Model
继承的任何属性,请使用以下命令:
type WithoutModel<T> = Omit<T, keyof Model>
const {
userId,
username,
email,
confirmed,
password,
isAdmin
} = req.body as WithoutModel<User>
如果我正确阅读了您的问题,Sequelize 为此提供了 Utility Type Attributes<M extends Model>
。 https://sequelize.org/docs/v6/other-topics/typescript/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.