Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrain keys using value type [duplicate]

Tags:

typescript

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.

like image 261
zoul Avatar asked Jun 23 '26 00:06

zoul


2 Answers

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

like image 97
Yury Tarabanko Avatar answered Jun 25 '26 01:06

Yury Tarabanko


You could use the following

function lookup<Object, Key extends keyof Object>(object: Object, key: Object[Key] extends string ? Key: never)
like image 21
Murat Karagöz Avatar answered Jun 25 '26 00:06

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!