EN
TypeScript / JavaScript - immutable enums
9 points
In this short article, we would like to show how to create immutable enums in JavaScript / TypeScript.
During compilation, enums are converted to JavaScript objects that can be changed, which can lead to bugs.
It is necessary to freeze the enum object.
Practical example (JavaScript):
xxxxxxxxxx
1
const CurrencyEnum = {
2
'USD': 1,
3
'EUR': 2,
4
'GBP': 3,
5
'CHF': 4,
6
'PLN': 5
7
};
8
9
Object.freeze(CurrencyEnum); // <---------- makes CurrencyEnum as read-only
10
11
// now CurrencyEnum is read-only
Practical example (TypeScript):
xxxxxxxxxx
1
enum CurrencyEnum {
2
USD = 1,
3
EUR = 2,
4
GBP = 3,
5
CHF = 4,
6
PLN = 5
7
};
8
9
Object.freeze(CurrencyEnum); // <---------- makes CurrencyEnum as read-only in pure JavaScript
10
11
// now CurrencyEnum is read-only from pure JavaScript
Note:
Object.freeze()
was introduced in ES5 (ECMAScript 2009).