I am trying to create a function in typescript to override the default values of an object with the values given in another object.
Basically it should take in 2 objects and add the non-null properties of 2nd object to the first object and return the modified obj.
I could use destructuring like this {...a, ...b} but then if there are any null values in the b object, those would override the values in a object.
Here is a function I wrote, unfortunately, can't understand what typescript is complaining about.
function assignIfPresent<T extends Record<string, unknown>>(origObj: T, additions:Partial<T> ) {
for (const propName in additions) {
if (additions[propName])
origObj[propName] = additions[propName];
}
return origObj;
}
error at origObj[propName]
const propName: Extract<keyof T, string>
Type 'T[Extract<keyof T, string>] | undefined' is not assignable to type 'T[Extract<keyof T, string>]'.
Type 'undefined' is not assignable to type 'T[Extract<keyof T, string>]'.
UseCase:
class User {
public firstName!: string;
public lastName!: string;
public gender?: string;
}
const newUser = new User();
newUser.lastName = "Biden"
const userDetails: Partial<User> = {
firstName: "Joe",
lastName: undefined,
}
console.log(assignIfPresent(newUser, userDetails)) //[LOG]: { "lastName": "Biden", "firstName": "Joe" }
console.log({...newUser, ...userDetails}) //[LOG]: { "firstName": "Joe" }
would be great if anyone can help me out.