My challenge involves a state object and an update object that will merge with the state object. However, if the update value is null
, it should be deleted instead of just combining them using {...a, ...b}
.
const obj = {
other: new Date(),
num: 5,
str: "original string"
}
const objUpdate: Partial<typeof obj> = {
num: 6,
str: "updated string"
}
The task at hand is to loop through the update object and update the original object accordingly. Ideally, I would approach it like this:
Object.entries(objUpdate).forEach(([k,v]) => {
if (v === undefined) return;
if (v === null){
delete obj[k]; // <-
return;
}
obj[k] = v; // <-
})
However, I encounter an error indicating that
No index signature with a parameter of type 'string' was found on type '{ other: Date; num: number; str: string; }'
. It seems like Typescript needs clarification on the type of k
, so I explicitly define it as:
Object.entries(objUpdate).forEach(([k,v]) => {
if (v === undefined) return;
if (v === null){
delete obj[k as keyof typeof objUpdate];
return;
}
obj[k as keyof typeof objUpdate] = v; // <-
})
Now, I face an error stating that
Type 'string | number | Date' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
- Is there a way to assist Typescript in correctly inferring typings in this scenario?
- Is there a more effective method to achieve my goal?