简体   繁体   中英

Typing attributes in a Sequelize Model class

Say I have Contact, which is a Sequelize model defined like this:

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 ). Using Contact as the type works, but it's not quite correct because it should really only be the attributes.

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:

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM