I'm looking to implement a generic function which accepts a single type argument "T" which is an object. It uses keyof T
to specify the first argument to the function "property". Now the part I can't get working, I want to use the type of T[typeof property]
to specify the type of the second argument to the function "value".
This gets me close to the ideal usage,
type Person = {
name: string;
age: number;
};
function filter<T>(property: keyof T, value: T[typeof property]) {
return `${property} ${value}`
}
filter<Person>("name", 123);
With the above we get type checking for the "property" argument, correctly restricting it to only "name" or "age". Unfortunately for the value argument it accepts either a number or string, so it seems to be creating a union of all the keyof types of Person.
Any ideas?
Copyright Notice:Content Author:「rssfrncs」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53299743/generic-function-and-index-types