Search code examples
typescriptenumsindex-signature

Can I use an index signature to create an array of descriptions for an enum?


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.


Solution

  • 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: