Search code examples
typescriptobjectkeyof

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?

(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');