类型“Type[T]”上不存在属性“key”

时间:2021-06-30 16:03:09

标签: typescript typescript-generics union-types

当我检查 index 是否为“名称”时,为什么它不起作用。 typeScript 应该捕捉到这一点,知道如果 index 等于“name”,那么 value 就是 name 对象。

interface Person {
  name: {
    text: string
    id: number
  };
  age: number;
}

const person: Person = {
  name: {
    text: 'me', 
    id: 789
  }, 
  age: 30
};

const changePerson = <T extends keyof Person>(index:T, value: Person[T]): void => {

  if  (index === 'name') {
    value.text = 'he'
  }

  person[index] = value;
  
}

// OK
changePerson("name", { text: 'you', id: 123});

// Compilation error
changePerson("name", 32);

TS 游乐场:Link

我的猜测是,当泛型类型与联合类型一起使用时,TS 无法像我预期的那样缩小范围。

但我对具体细节感到非常困惑。请给我一个详细的解释。谢谢大家。

0 个答案:

没有答案