Created
August 9, 2018 11:10
-
-
Save infloop/366bb02924ff8ccc180d31cb91b870af to your computer and use it in GitHub Desktop.
Assign with type checking (typescript)
This file contains hidden or 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]; | |
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>; | |
type Omit<T, K extends keyof T> = Pick<T, ({ [P in keyof T]: P } & { [P in K]: never } & { [x: string]: never })[keyof T]>; | |
export function assign<T extends NonFunctionProperties<Omit<S, K>>, S extends Object, K extends keyof S>(target: T, source: S, exclude?: K[]): void { | |
Object.keys(source).forEach(key => { | |
// exclude Object methods | |
if (typeof source[key] === 'function') { | |
return; | |
} | |
// exclude excluded Object keys | |
if ((exclude || []).indexOf(key) >= 0) { | |
return; | |
} | |
target[key] = source[key]; | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment