Close

TypeScript - Heterogeneous Enums

[Updated: Oct 13, 2018, Created: Oct 13, 2018]

In TypeScript enums can be mixed with numeric values and string values.

Example

enum Align {
    LEFT = 'left',
    CENTER = 0,
    RIGHT = 'right'
}

for (let key in Align) {
    console.log(`key=${key}, value=${Align[key]}`);
}

Output

key=0, value=CENTER
key=LEFT, value=left
key=CENTER, value=0
key=RIGHT, value=right

As seen in the output, the numeric enum element still has reversed mapping while string enum does not have that.

TypeScript team does not recommend to mix the enum value types:

Unless you're really trying to take advantage of JavaScript's runtime behavior in a clever way, it's advised that you don't do this.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.1
Heterogeneous Enums Select All Download
  • typescript-heterogeneous-enums
    • heterogeneous-enum-example.ts

    See Also