![](/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.