Home > other >  Typescript issue with dynamic types of argument
Typescript issue with dynamic types of argument

Time:07-27

I'm trying to make getter and setter in Typescript and facing issues with dynamic types of arguments.

interface PersonType {
  name: string;
  age: number;
}

const person: PersonType = {
  name: '',
  age: 0
};

const setPersonKey = ({ key, value }: { key: keyof PersonType; value: PersonType[keyof PersonType] }) => {
  person[key] = value; // ERROR -> Type 'string | number' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
}


const getPersonKey = ({ key }: { key: keyof PersonType; }): PersonType[keyof PersonType] => {
  return person[key];
}

I have 3 issues with the above code

  1. person[key] throws an error in setPersonKey function
  2. value type is not dynamic based on the key passed in setPersonKey function
  3. return type of getPersonKey function is not dynamic based on key value

Would really appreciate a reference doc and an explanation of the solution.

Typescript playground for testing: https://www.typescriptlang.org/play

CodePudding user response:

The problem is with the argument type - { key: keyof PersonType; value: PersonType[keyof PersonType] } is an object with a key property, that is a key of PersonType(OK), and a value property that is of the same type as any value of PersonType, not necessarily the same as key.

Try this to make the compiler understand that key and value refer to the same proprty of PersonType::

const setPersonKey = <K extends keyof PersonType>({ key, value }: { key: K; value: PersonType[K] }) => {
  person[key] = value;
}
  • Related