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

How to return a specific type of object property in TypeScript?

Lets say I have a list of flags in an object as below:

type Flags = {
  flag1: string,
  flag2: string,
  flag3: boolean,
  flag4: number
}

// const myFlags: Flags = {
//   flag1: 'value 1',
//   flag2: 'value 1',
//   flag3: true,
//   flag4: 12
// }

I want to write a function getFlag that looks like this:

function getFlag(flag: keyof Flags): any { 
   // return myFlags[flag]
}

Instead of returning any, how can I return the type of flag that getFlag is being called with?

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

(to make this maybe easier, we can limit the flag types to boolean, string and number, but instead of returning boolean | string | number, I still want to get the specific property type)

>Solution :

Make the function generic so that the type of the string being passed in can be used to look up the associated type of the value on the object.

function getFlag<T extends keyof Flags>(flag: T) { 
   return myFlags[flag]
}
const result = getFlag('flag1');

You could go a step further and return the exact type with as const.

 const myFlags = {
   flag1: 'value 1',
   flag2: 'value 1',
   flag3: true,
   flag4: 12
 } as const;

function getFlag<T extends keyof typeof myFlags>(flag: T) { 
   return myFlags[flag]
}
const result = getFlag('flag1');
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