Imagine a scenario where I am working with the following JS function:
function fetchValue(keyName) {
return x => x[keyName];
}
Is it possible to define fetchValue
in such a way that Typescript's type inference automatically determines the output based on the provided examples:
const obj1 = { name: "John", age: 30 };
const obj2 = { name: "Alice", age: 25 };
const result1 = fetchValue("name")(obj1); // result1 should be of type string
const result2 = fetchValue("age")(obj2); // result2 should be number
const getName = fetchValue("name");
// getName should have signature: <T> (t: T) => T["name"]
const getAge = fetchValue("age");
// getAge should have signature: <T> (t: T) => T["age"]
If instead of passing a parameter keyName
, I knew the fixed property name, I could potentially do something like this:
function fetchName():
<TName> (x: { name: TName }) => TName
or explore a slightly different route towards achieving my goal:
function fetchFirstProperty():
<T> (x: T) => T["first]
But how can I make Typescript assign the argument of the function as the property name?
I've experimented with various approaches, but haven't found success yet:
function getPropertyKey<K> (keyName: K):
<TProp> (t: { [K]: TProp }) => TProp {
return x => x[keyName];
}
Typescript seems reluctant to accept a generic K
as the indexing type.