英文:
Can't edit an attribute, error Type 'string' is not assignable to type 'never' with TypeScript
问题
我想在 TypeScript 和 React 中编辑对象的属性,但是我遇到以下错误:
Type 'string' is not assignable to type 'never'
,尽管在此之前我已经检查了该属性的类型:
const familySetter = (newValue: string, attributeToSet: keyof Family) => {
setNewFamily((currNewFam) => {
if (!currNewFam) return;
const newNewFam: Family = { ...currNewFam };
if (typeof newNewFam[attributeToSet] === 'string') {
newNewFam[attributeToSet] = newValue; // 在此行出现错误
}
return newNewFam;
});
};
英文:
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;
});
};
答案1
得分: 0
以下是您要翻译的内容:
当您的类属性具有多种类型时(例如字符串和数字),将会发生这种情况
class Family {
test: string;
test2: number;
};
在这种情况下,编译器将不知道newNewFam[attributeToSet]
是哪种类型之一
一种解决方法是通过扩展keyof Family
来声明您的方法,并声明值的类型为Family[K]
const familySetter = <K extends keyof Family>(newValue: Family[K], attributeToSet: K)
if (typeof newNewFam[attributeToSet] === 'string')
不足以,因为它依赖于函数参数在运行时进行评估
完整示例如下:
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;
});
};
英文:
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;
});
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论