I have an object with values of type string
and number
:
interface Person {
name: string;
age: number;
}
I have a function that changes the object with one parameter as the field index, and the other as the field value:
const person = {name: "Fred", age: "30"};
const changePerson = (index: keyof Person, value: string | number): void => {
person[index] = value;
}
The problem is that, as TypeScript sees it, index
can be "name" and value
can be a number, but that would never happen. I'm not sure how to link index
and value
to tell TypeScript that the types are linked in a specific way.
Can anyone help?
I was able to get rid of the errors by using a case statement but that would not be transpiled out as TypeScript normally would:
const changePerson = (index: keyof Person, value: string | number): void => {
switch(index) {
case "name":
person[index] = value as string;
break;
default:
person[index] = value as number;
}
}
You could do it with generics: <T extends keyof Person>(index: T, value: Person[T]): void
This basically tells the type system that the second parameter has to be whatever the first one points to on the type.
The full example on Typescript playground
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.