In my attempt to configure a generic with the parameter serving as the key of another object, I have found success using extends keyof
when both types are provided as parameters to the function.
However, I encountered an issue when the type that provides the list of keys is not an argument, but instead a generic type. In this scenario, TypeScript requires both generic types to be explicitly set.
Take a look at the code snippet below:
interface Bar {
z: string;
t: number;
}
declare function foo1<T extends keyof Bar>(x: T)
let t1 = foo1('z');
declare function foo2<K, T extends keyof K>(x: T)
let t2 = foo2<Bar>('t');
declare function foo3<T>(x: T)
let t3 = foo3<keyof Bar>('t');
The function foo2
encountered a failure because the second type T
was left unspecified. Personally, I believe TypeScript should be able to infer the correct typings without the need for an explicit declaration of the second type.
To work around this limitation, I resorted to using foo3
. Although it functions, it is not as elegant to work with. Is there a way for TypeScript to automatically perform this inference, or would it require a feature request or bug report to the TypeScript team?