Skip to content

Instantly share code, notes, and snippets.

@mycarrysun
Created December 9, 2019 21:36
Show Gist options
  • Save mycarrysun/701093224b84d8fe58f7fb74ffd51744 to your computer and use it in GitHub Desktop.
Save mycarrysun/701093224b84d8fe58f7fb74ffd51744 to your computer and use it in GitHub Desktop.
Typescript Decorator function to populate the class properties with the first argument as an object
export function InitsWithProps<T extends {new(...args: any[]): {}}>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
if (args && args.length) {
Object.assign(this, args[0]); //args[0] must be an object
}
}
};
}
@mycarrysun
Copy link
Author

Usage

@InitsWithProps
export class ExampleClass {
  id: number;
  text: string;
}

const example = new ExampleClass({ id: 1, text: 'example here' })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment