Skip to content

Instantly share code, notes, and snippets.

@infloop
Created August 9, 2018 11:10
Show Gist options
  • Save infloop/366bb02924ff8ccc180d31cb91b870af to your computer and use it in GitHub Desktop.
Save infloop/366bb02924ff8ccc180d31cb91b870af to your computer and use it in GitHub Desktop.
Assign with type checking (typescript)
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