Reputation: 3643
I want to know if it’s possible in typescript to have something like:
func<T,V>(prop: keyof T: V)
interface IIntf{
prop1: string,
prop2: number
}
func<IIntf, string>(‘prop1’) //OK
func<IIntf, string>(‘prop2’) //NOT OK (prop2 is of type number)
Upvotes: 1
Views: 52
Reputation: 3501
This is possible using mapped types and type inference, like in the following type that will extract only keys with specified type:
type ObjectKeysWithType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never
}[keyof T];
The reasoning here is:
T[K] extends
) the desired type (V
){ .. }[keyof T
Upvotes: 1