1

Suppose I have the following enum:

export enum ApiRole {
    User = 1,
    SuperUser = 2,
    Restricted = 3,
}

Is there a way for me to easily create an array that I can use these enum values to index that will return a string value I can use as a description?

I have tried this:

export const ApiRoleDescriptions: {[role: number]: string} = {
    1: 'Normal User',
    2: 'Super User',
    3: 'Restricted',
}

But this method requires me to manually set the numeric values of each enum value which is a bit of a maintainability problem.

At the end of the day I'd like to be able to write something like ApiRoleDescriptions[ApiRole.User] directly somewhere else in my code.

EDIT: Looks like the answer to my question at the time of writing is no - at least until this PR is merged in to typescript, which currently has a milestone of 3.3/3.4. However, I am still looking for some sort of method to accomplish this in the meantime.

ldam
  • 4,412
  • 6
  • 45
  • 76
  • "this method requires me to manually set the numeric values of each enum value" --- if not manually how else would TS know `ApiRole.User` is a `Normal User`? – zerkms Feb 26 '19 at 08:57
  • I'd like to be able to use the enum values with their names in the definition of the indexer. So something like `export const ApiRoleDescriptions: {[role: ApiRole]: string} = { ApiRole.User: 'Normal User', }` etc. – ldam Feb 26 '19 at 09:03
  • Basically, I just think it's weird that an index signature requires a `string` or `number` value, and an enum can be either `string` or `number` valued, but it still can't be used in an index signature. – ldam Feb 26 '19 at 09:05
  • `const ApiRoleDescriptions: {[k in ApiRole]: string} = {` – zerkms Feb 26 '19 at 09:07

1 Answers1

2

You would declare it like this:

export const ApiRoleDescriptions: {[k in ApiRole]: string} = {
    1: 'Normal User',
    2: 'Super User',
    [ApiRole.Restricted]: 'Restricted',
}

in ApiRole would ensure that all keys are of known enum values and that all values are assigned.

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • This is almost what I want, in that it is pulling the values from `ApiRole`, but it still requires me to define them in format `'1': 'Normal User'` instead of `ApiRole.User: 'Normal User'` – ldam Feb 26 '19 at 09:46