Languages
[Edit]
EN

TypeScript / JavaScript - immutable enums

9 points
Created by:
Gigadude
371

In this short article, we would like to show how to create immutable enums in JavaScriptTypeScript.

Problem overview

During compilation, enums are converted to JavaScript objects that can be changed, which can lead to bugs.

Problem solution

It is necessary to freeze the enum object.

Practical example (JavaScript):

// ONLINE-RUNNER:browser;

const CurrencyEnum = {
    'USD': 1,
    'EUR': 2,
    'GBP': 3,
    'CHF': 4,
    'PLN': 5
};

Object.freeze(CurrencyEnum);  //  <---------- makes CurrencyEnum as read-only

// now CurrencyEnum is read-only

Practical example (TypeScript):

enum CurrencyEnum {
    USD = 1,
    EUR = 2,
    GBP = 3,
    CHF = 4,
    PLN = 5
};

Object.freeze(CurrencyEnum);  //  <---------- makes CurrencyEnum as read-only in pure JavaScript

// now CurrencyEnum is read-only from pure JavaScript

Note: Object.freeze() was introduced in ES5 (ECMAScript 2009).

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join