[英]Typing attributes in a Sequelize Model class
Say I have Contact, which is a Sequelize model defined like this:假设我有 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}`;
}
In the definition of createContact
I have the options argument which should contain the attributes (ie id , first_name , last_name ).在
createContact
的定义中,我有options参数,它应该包含属性(即id 、 first_name 、 last_name )。 Using Contact
as the type works, but it's not quite correct because it should really only be the attributes.使用
Contact
作为类型有效,但它不太正确,因为它实际上应该只是属性。
I could define a separate type containing these attributes, but I would still have to write them within the class as well.我可以定义一个包含这些属性的单独类型,但我仍然必须在类中编写它们。 How can I avoid this redundancy, and define the attributes in only one place?
如何避免这种冗余,并仅在一个地方定义属性?
Use OnlyAttrs<T>
to extract only attributes from a type:使用
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>;
then in the method:然后在方法中:
public static createContact = (options: ContactAttrs): Contact => new Contact(options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.