I have a TypeScript function a bit like this:
function lookup<Object, Key extends keyof Object>(object: Object, key: Key): any
Now, can I constrain the key type using the type of the produced value? Example:
interface Animal {
name: string;
legs: number;
}
Now can I constrain lookup to only allow keys that have a string value? Ie. that calling lookup(animal, "name") would be valid, but lookup(animal, "legs") would be not.
Some play with generics and conditional types might do the trick
type KeysOfType<T, P> = { [K in keyof T]: P extends T[K] ? K : never }[keyof T]
function lookup<T, K extends KeysOfType<T, string>>(object: T, key: K): T[K] {
return object[key];
}
Playground
You could use the following
function lookup<Object, Key extends keyof Object>(object: Object, key: Object[Key] extends string ? Key: never)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With