Tomas
Tomas

Reputation: 3436

String enums as object indexing types in TypeScript

Consider following Enum:

export const SOME_STRING_ENUM {
  ONE = 'one',
  TWO = 'two'
}

Now let's assume, I need some value mapper to this enum, I figured out such a monstrosity:

export type eKey = keyof typeof SOME_STRING_ENUM;
export const mapper: {[k in eKey]?: string} = {
  [SOME_STRING_ENUM[SOME_STRING_ENUM.ONE]]: 'This is label for one'
  [SOME_STRING_ENUM[SOME_STRING_ENUM.TWO]]: 'This is label for two'
}
// please note referring to labels via [E[E.K]] not via just plain E.K

End then obtaining those mapper keys is even more ridiculous to be hones:

  public mapEnum(reason: SOME_STRING_ENUM) {
    return mapper[SOME_STRING_ENUM[reason]];
  }

Well... above works well. But it's ugly as hell and I'm not fully convinced where I went so wrong that I need to use double referring to actually make myself happy with referring object by label... My expected solution would be as simple as:

export type eKey = keyof typeof SOME_STRING_ENUM;
export const mapper: {[k in eKey]?: string} = {
  [SOME_STRING_ENUM.ONE]: 'This is label for one'
  [SOME_STRING_ENUM.TWO]: 'This is label for two'
}

  public mapEnum(reason: SOME_STRING_ENUM) {
    return mapper[reason];
  }

Would this be possible with string enumerators? Or, as always, I get confused somewhere at the beginning?

Thanks for any help!

Upvotes: 0

Views: 85

Answers (1)

mbdavis
mbdavis

Reputation: 4010

You can instead use the values of the enum, rather than the keys as you have here.

To do this, you extract object values via T[keyof T] - where T is your enum type (typeof SOME_STRING_ENUM).

This gives you pretty much as you had written the second example:

export enum SOME_STRING_ENUM {
    ONE = 'one',
    TWO = 'two'
}

export type eKey = typeof SOME_STRING_ENUM[keyof typeof SOME_STRING_ENUM];

export const mapper: { [k in eKey]: string } = {
    [SOME_STRING_ENUM.ONE]: 'This is label for one',
    [SOME_STRING_ENUM.TWO]: 'This is label for two',
}

function mapEnum(reason: SOME_STRING_ENUM) {
    return mapper[reason];
}

Playground link here

Upvotes: 2

Related Questions