Created
June 28, 2019 16:05
-
-
Save NickStrupat/542d8d1c12477dbf69d83897a1537d3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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