I want to edit original object data without mutation and possibly without deep cloning the original object. I found Immer. Using its produce function works just fine. But when I want to delete original object property I get an error The operand of a 'delete' operator must be optional. which is understandable.
interface User {
name: string;
surname: string;
age: number;
}
const user: User = {
name: 'John',
surname: 'Small',
age: 20
}
const changedUser = produce(user, (draft) => {
draft.name = 'Mark';
delete draft.age; // The operand of a 'delete' operator must be optional.
})
I can force its Base type like produce<Partial<User>>(/* ... */) but I think it's ugly and if you would like to edit nested objects, you would have to sanitize possible undefined errors. Are there any more suitable approaches?