Use string literals for the TypeScript enum values
Let's say that we have the following TypeScript enum:
enum Theme {
DEFAULT,
LIGHT,
DARK,
}
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:
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 {
DEFAULT = 0,
LIGHT = 1,
DARK = 2,
}
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);
let theme: Theme.DEFAULT = 'Default';