0

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

4
  • why didn't you do const person : PersonType = {? Commented Jul 26, 2022 at 14:01
  • 1
    Have tried that, but the error does not change. I will update the question to remove this confusion. Commented Jul 26, 2022 at 14:03
  • typescript-typings is a tag very specifically regarding a type library system and indicates clearly in all-caps "DO NOT USE IT AS A SYNONYM OF TYPES". Commented Jul 26, 2022 at 14:23
  • @crashmstr was not aware, thanks! Commented Jul 26, 2022 at 14:41

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your quick help. Working sample here replit.com/@RajRohit/AutopickType#index.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.