← #7 Use underscores to represent a number

Use string literals for the TypeScript enum values

Topics: TypeScript

Let's say that we have the following TypeScript enum:

enum Theme {

If you don't set the values for enum, they will be set to incremental numbers by default.

So Theme.DEFAULT, Theme.LIGHT and Theme.DARK will take the value of 0, 1, 2, respectively. It is more hard to debug:

console.log(Theme.DARK);    // 2

Even if we set the number for enum values, it is still possible for us to set an invalid value for a variable whose type is the enum:

enum Theme {
LIGHT = 1,
DARK = 2,

// TypeScript doesn't throw errors
const theme: Theme.DEFAULT = 3;

Due to these reasons, it's advised to use string literals for the enum values. The Theme enum should look like as follow:

enum Theme {
DEFAULT = 'Default',
LIGHT = 'Light',
DARK = 'Dark',

console.log(Theme.DARK); // 'Dark'
let theme: Theme.DEFAULT = 'Default'; // ERROR
Fix a typo or suggest an improvement
#9 Remove a property from an object