I am trying to create a “assign default” function in typescript, where it loops through the keys of the source
, and if that value by the same key is nullish in the target
, it will use the value from the source
instead. Here’s my attempt:
const assignDefault = <T, U>(target: T, source: U): T & U => {
Object.keys(source).forEach(key => {
// typecasted as Object.keys returns string[]
const prop = target[key as keyof T]
if (typeof prop === 'undefined' || typeof prop === 'null') {
// Error: Type 'U[keyof U]' is not assignable to type 'T[keyof T]'.
target[key as keyof T] = source[key as keyof U]
}
})
return target // Error: Type 'T' is not assignable to type 'T & U'.
}
I borrowed the generics from how Object.assign
is typed in typescript: ObjectConstructor.assign<T, U>(target: T, source: U): T & U;
But I couldn’t find a way to get around these errors.