[英]Typing attributes in a Sequelize Model class
假設我有 Contact,它是一個 Sequelize 模型,定義如下:
class Contact extends Model<Contact> {
id: number;
first_name: string;
last_name: string;
public static createContact = (options: Contact): Contact => new Contact(options);
public getName = (): string => `${this.first_name} ${this.last_name}`;
}
在createContact
的定義中,我有options參數,它應該包含屬性(即id 、 first_name 、 last_name )。 使用Contact
作為類型有效,但它不太正確,因為它實際上應該只是屬性。
我可以定義一個包含這些屬性的單獨類型,但我仍然必須在類中編寫它們。 如何避免這種冗余,並僅在一個地方定義屬性?
使用OnlyAttrs<T>
僅從類型中提取屬性:
// extract props that are NOT functions
type OnlyAttrs<T> = {
[K in {
[K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? never : K;
}[keyof T]]: T[K];
};
// then this type only includes attributes
type ContactAttrs = OnlyAttrs<Contact>;
然后在方法中:
public static createContact = (options: ContactAttrs): Contact => new Contact(options);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.