简体   繁体   English

无法编辑属性,错误类型“字符串”不可分配给类型“从不”与 TypeScript

[英]Can't edit an attribute, error Type 'string' is not assignable to type 'never' with TypeScript

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:我想在 TypeScript 和 React 中编辑 object 的一个属性,但我收到以下错误:尽管我之前检查过此属性的类型,但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; //error at this line

      }
      return newNewFam;
    });
  };

It will occured when your class properties have several types (for sample string and number)当您的 class 属性有多种类型时(示例字符串和数字),它就会发生

class Family {
    test: string;
    test2: number;
};

in that case the compilator will not know if newNewFam[attributeToSet] is of one type or another在那种情况下,编译器将不知道newNewFam[attributeToSet]是一种类型还是另一种类型

one solution is to declare your method by extending the keyof Family and say value is of type Family[K]一种解决方案是通过扩展 keyof Family 来声明您的方法,并说值是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 if if (typeof newNewFam[attributeToSet] === 'string')不够,因为它在运行时根据 function 参数进行评估

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;
    });
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM