I am looking to create a utility function that takes an instance and an object as input, and then updates the instance with the values from the provided object fields. Below is the code for the utility function:
function updateEntity<T, K extends keyof T>(
entity: T,
updateInput: { [key in K]: T[K] },
): void {
return Object.keys(updateInput).forEach((key) => {
entity[key as K] = updateInput[key as K];
});
}
Here I have defined an instance and an update interface:
class Animal {
name: string = 'no name';
isMale: boolean = false;
}
type Input = Partial<{
name: string;
}>;
const input: Input = {
name: 'str'
};
const cat = new Animal();
updateEntity(cat, input); // This line produces an error
I am encountering the following error:
Argument of type 'Partial<{ name: string; }>' is not assignable to parameter of type '{ name: string; }'.
Types of property 'name' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.(2345)
I am struggling to fully understand this error message. My goal was to partially update the original instance with the given input data.
The input should be a subset of the original instance without any additional fields.
Here is a link to the playground: link
What could I be overlooking?