Reputation: 1223
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 (i.e. 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?
Upvotes: 0
Views: 413
Reputation: 394
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);
Upvotes: 1