Amin Paks
Amin Paks

Reputation: 276

TypeScript narrow down the keys of indexable type by its value types

Given we have a generic indexable type how can I retrieve only the types of its values to be able to narrow down to only some of the keys?

// imagine check is a function and its second argument only allows the property `a` as it's string and raise an error if 'b' is passed
const test2 = check({ a: 'string', b: 22 }, 'b'); // error only 'a' is allowed
const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok returns 'str2'

Upvotes: 2

Views: 604

Answers (1)

jcalz
jcalz

Reputation: 329268

Sure, you can do this by using conditional and mapped types to extract just the keys of an object type T whose values match a value type V:

type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
declare function check<T>(obj: T, k: KeysMatching<T, string>): string;

const test1 = check({ a: 'string', b: 22 }, 'b'); // error 
const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok 

Hope that helps. Good luck!

Upvotes: 4

Related Questions