Property `key` does not exist on type 'Type[T]'

Viewed 56

When I check if the index is "name", why it doesn't work. The typeScript should catch this, knowing that if the index is equal to "name", then value is the name object.

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 Playground: Link

My guess is that when generic types are used with union types, TS is unable to narrow it as I would expect.

But I am very confused about the specific details. Please give me a detailed explanation. Thank you all.

0 Answers
Related