Typescript- how to get the type of certain key on object?

const map ={
  a:1,
  b:'Hello world',
  c:()=>99,
  d:()=>'Love',
  e:()=>'adoration'
}

type LoveFunctionNameInString = keyof typeof map & ?

const result: LoveFunctionNameInString = 'd' | 'e'

I would like a type that points to the methods of string return type in ‘map’ object, so whenever I assign the type ‘LoveFunctionNameInString’ to a variable, Typescript would suggest me only ‘d’ | ‘e’ (because they are function of string return type) without ‘a’ | ‘b’ | ‘c’.

>Solution :

Inspired by this answer
Here’s your working code –

const map ={
  a:1,
  b:'Hello world',
  c:()=>99,
  d:()=>'Love',
  e:()=>'adoration'
}

type KeysMatching<T, V> = NonNullable<
  { [K in keyof T]: T[K] extends V ? K : never }[keyof T]
>;

type LoveFunctionNameInString = KeysMatching<typeof map, () => string>;

Leave a Reply