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 insetPersonKeyfunctionvaluetype is not dynamic based on thekeypassed insetPersonKeyfunction- return type of
getPersonKeyfunction is not dynamic based onkeyvalue
Would really appreciate a reference doc and an explanation of the solution.
Typescript playground for testing: https://www.typescriptlang.org/play
const person : PersonType = {?typescript-typingsis a tag very specifically regarding a type library system and indicates clearly in all-caps "DO NOT USE IT AS A SYNONYM OF TYPES".