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

Time:01-17

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'.

CodePudding user response:

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>;
  • Related