2

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.

zoul
  • 102,279
  • 44
  • 260
  • 354

2 Answers2

3

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

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
1

You could use the following

function lookup<Object, Key extends keyof Object>(object: Object, key: Object[Key] extends string ? Key: never)
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107