My goal is to dynamically update one object using another object of the same type.
This object contains properties of different types:
type TypeOne = 'good' | 'okay';
type TypeTwo = 'default' | 'one';
interface Option {
year: TypeOne,
date?: TypeTwo
}
const currentData: Option = {
year: 'good',
date: 'default'
}
Here is the second object used to update currentData
:
const newData: Option = {
year: 'okay',
}
I have an array used to dynamically index the object:
const params: (keyof typeof currentData)[] = ['year', 'date'];
Below is the updating process where the problem arises:
params.forEach((param) => {
currentData[param] = newData[param] // error: currentData[param] is inferred as type 'never'
if(param === 'year'){ // if I would typecheck param, there would be no error
currentData[param] = newData[param] // But then it won't be dynamic anymore
}
});
It doesn't matter if I check if param
exists in currentData
, as it is already of type keyof typeof currentData
.
I could check the parameter explicitly, but that would remove the dynamic aspect.
The issue seems to stem from currentData[param]
being inferred as all possible values, making it uncertain when assigning a new value.
However, both currentData
and newData
are of the same type and are "in sync" since they use the same parameter to index both objects when assigning values. Hence, in theory, there is enough information available.
Is there a way to let TypeScript know that the objects are "synced" in this scenario?