I want to edit an attribute from an object in TypeScript and React but I get the following error:
Type 'string' is not assignable to type 'never'
despite the fact that I check the type of this attribute before :
const familySetter = (newValue: string, attributeToSet: keyof Family) => {
setNewFamily((currNewFam) => {
if (!currNewFam) return;
const newNewFam: Family = { ...currNewFam };
if (typeof newNewFam[attributeToSet] === 'string') {
newNewFam[attributeToSet] = newValue; //error at this line
}
return newNewFam;
});
};
CodePudding user response:
It will occured when your class properties have several types (for sample string and number)
class Family {
test: string;
test2: number;
};
in that case the compilator will not know if newNewFam[attributeToSet]
is of one type or another
one solution is to declare your method by extending the keyof Family and say value is of type Family[K]
const familySetter = <K extends keyof Family>(newValue: Family[K], attributeToSet: K)
the if if (typeof newNewFam[attributeToSet] === 'string')
is not enought because it's evaluate at runtime dependings on function parameter
complete sample is
class Family {
test: string;
test2: number;
};
const familySetter = <K extends keyof Family>(newValue: Family[K], attributeToSet: K) => {
setNewFamily((currNewFam) => {
if (!currNewFam) return;
const newNewFam: Family = { ...currNewFam };
if (typeof newNewFam[attributeToSet] === 'string') {
newNewFam[attributeToSet] = newValue;
}
return newNewFam;
});
};