Created
June 11, 2019 10:34
-
-
Save hasparus/7543e33518626a1ea132e909a9963f2a to your computer and use it in GitHub Desktop.
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 Defined<T extends object> = { [K in keyof T]: Exclude<T[K], undefined> }; | |
type Assign<T1, T2> = { | |
[K in keyof T1 | keyof T2]: K extends keyof T2 | |
? T2[K] extends undefined | |
? K extends keyof T1 | |
? T1[K] | |
: never | |
: T2[K] | |
: K extends keyof T1 | |
? T1[K] | |
: never | |
}; | |
/** | |
* Assign values of obj2 to shallow copy of obj1 if they're not undefined | |
*/ | |
function assign<T1 extends Record<string, any>, T2 extends Record<string, any>>( | |
obj1: T1, | |
obj2: T2 | |
): Assign<T1, T2> { | |
const result = { ...obj1 }; | |
for (const [key, val] of Object.entries(obj2)) { | |
if (val !== undefined) { | |
result[key as keyof T1] = val; | |
} | |
} | |
return result as Assign<T1, T2>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment