Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading