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
person[key]
throws an error insetPersonKey
functionvalue
type is not dynamic based on thekey
passed insetPersonKey
function- return type of
getPersonKey
function is not dynamic based onkey
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;
}