Understanding Enums in TypeScript

Jared Youtsey
1 min readDec 17, 2018

--

We’ve all seen this pattern at some point:

export class Things {
static readonly VALUE_1 = 'VALUE_1';
static readonly VALUE_2 = 'VALUE_2';
static get ALL_STATES() {
return [
Things.VALUE_1,
Things.VALUE_2
];
}
}

This is not necessary in TypeScript. TS allows us to get the string value of a numerical enum very easily. We also cannot type variables as thing: Things because Things is a class, not a type.

The TypeScript Way

export enum Things {
VALUE_1,
VALUE_2
}

Wow, that was easy! Now I can thing: Things and be sure that the compiler enforces that I actually pass one of the enums values to it.

But, wait, I want string “VALUE_1” instead of 1 at some point. How do I get it?

const thing: Things = Things.VALUE_1;
console.log(thing); // 1
console.log(Things[thing]); // "VALUE_1"

If you always need the string value, then just build your enum with string values:

export enum Things {
VALUE_1 = 'VALUE_1',
VALUE_2 = 'VALUE_2'
}
const thing: Things = Things.VALUE_1;
console.log(thing); // "VALUE_1"

--

--

Jared Youtsey

Passionate about JavaScript and Angular. Pure front-end development for the past eight years or so…