Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created June 28, 2019 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/542d8d1c12477dbf69d83897a1537d3b to your computer and use it in GitHub Desktop.
Save NickStrupat/542d8d1c12477dbf69d83897a1537d3b to your computer and use it in GitHub Desktop.
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
export function getPropertyNames<T>(defaultInstance: T): NonFunctionPropertyNames<T>[] {
const memberNames = Object.getOwnPropertyNames(defaultInstance); // get all members of the instance
const propertyNames = memberNames.filter(x => typeof (defaultInstance as any)[x] != "function"); // filter out functions
return propertyNames as NonFunctionPropertyNames<T>[]; // cast as array of string union of non-function properties (ideally would be a string typed tuple but can't be done yet)
}
export function createFromObject<T>(constructor: { new(): T }, parameters: Partial<T>): T {
const newInstance = new constructor();
const propertyNames = getPropertyNames(newInstance);
for (let propertyName of propertyNames)
(<any>newInstance)[propertyName] = (<any>parameters)[propertyName];
return newInstance;
}
export function createFromObjects<T>(constructor: { new(): T }, parametersArray: Partial<T>[]): T[] {
return parametersArray.map(parameters => createFromObject<T>(constructor, parameters));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment