[英]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.