2

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'
Amin Paks
  • 276
  • 2
  • 15

1 Answers1

4

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!

jcalz
  • 264,269
  • 27
  • 359
  • 360