Skip to content
Index

[TypeScript] Why you might not want to use TypeScript enums

Tested with: TypeScript v5.6

Enums are a powerful way of modelling data constraints (through fixed values) in various programming language and databases.

However, TypeScript enums have some issues to consider before using them.

Issues

Increased complexity

TypeScript enums come with nuances and extra complexity that may not be worth the effort to use them, as can be seen from the issues below, the official docs, and the linked article at the bottom of this page.

Later on, simple alternatives are shown.

Increased code output size

Since enums are not natively supported in JavaScript, TypeScript enums are transpiled to JavaScript.

Albeit probably not a major issue, the generated JavaScript code is larger than necessary (compared to alternatives). This adds up if you use a lot of enums.

enum Size {
Small,
Medium,
Large,
}

… outputs to:

"use strict";
var Size;
(function (Size) {
Size[Size["Small"] = 0] = "Small";
Size[Size["Medium"] = 1] = "Medium";
Size[Size["Large"] = 2] = "Large";
})(Size || (Size = {}));

Subtle differences in behaviors between string and number enums

For other runtime vs compile-time differences, see: https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-runtime.

Not necessarily safer — number enums are not type-safe

You can still pass any value to an enum variable when using number enums. This can cause bugs that are hard to catch.

enum Size {
Small,
Medium,
Large,
}
function checkEnum(size: Size) {
console.log(size);
}
checkEnum(4); // This works in TypeScript 4.x

What should I use instead to achieve data integrity?

Use a union type.

type Status = "active" | "inactive" | "pending";

Or, a regular object defined with as const.

const Status = {
active: "active",
inactive: "inactive",
pending: "pending",
} as const;