I have a state object and an update object that will be combined with the state object, though null
in the update means delete so I can't just do {...a, ...b}
with them.
const obj = {
other: new Date(),
num:5,
str:"original string"
}
const objUpdate:Partial<typeof obj> = {
num:6,
str:"updated string"
}
The task: Iterate through the update object and apply its values to the original object. This is how I ideally would do it:
Object.entries(objUpdate).forEach(([k,v])=>{
if (v === undefined) return;
if (v === null){
delete obj[k]; // <-
return;
}
obj[k] = v; // <-
})
But at the indicated lines I get an error that No index signature with a parameter of type 'string' was found on type '{ other: Date; num: number; str: string; }'
. Ideally Typescript would know that k
is already keyof typeof objUpdate
(edit: here's possibly why) but I guess I can explicitly indicate that:
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; // <-
})
At the indicated line it complains that Type 'string | number | Date' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
- Is there a way to help Typescript infer typings correctly in this situation?
- Is there a better approach to what I am trying to accomplish?