Menu

Enums, Unions, and Erasable Syntax

Lesson 4: Enums, Unions, and Erasable Syntax

What is an enum?

An enum is a TypeScript feature that defines a named set of constants and generates a JavaScript object at runtime.

Option Example Generates runtime code? Works with Node.js type stripping?
Numeric enum enum Slot { Morning, Evening } Yes No
String enum enum Status { Pending = 'pending' } Yes No
Union of literals `type Status = 'pending' 'shipped'` No
as const object const Status = { Pending: 'pending' } as const Yes (plain JS object) Yes

Example

// Enum
enum OrderStatus {
  Pending = 'pending',
  Shipped = 'shipped',
  Delivered = 'delivered',
}
const s1: OrderStatus = OrderStatus.Shipped;

// Recommended modern alternative: as const object + derived union
const ORDER_STATUS = {
  Pending: 'pending',
  Shipped: 'shipped',
  Delivered: 'delivered',
} as const;

type OrderStatusValue = (typeof ORDER_STATUS)[keyof typeof ORDER_STATUS];
// 'pending' | 'shipped' | 'delivered'

const s2: OrderStatusValue = ORDER_STATUS.Shipped;
const s3: OrderStatusValue = 'shipped'; // Plain strings also work

How it works

  • An enum creates both a type and a runtime object. Numeric enums even create a reverse mapping (Slot[0] === 'Morning').
  • A string enum value cannot be replaced by the equivalent string: const s: OrderStatus = 'shipped' is an error.
  • Erasable syntax is TypeScript that can be removed without generating new code. Enums, namespaces with values, and parameter properties are not erasable.
  • The erasableSyntaxOnly compiler option reports non-erasable syntax as errors. Turn it on if you run code with Node.js type stripping or tools that only remove types.
  • Decorators (@log) follow the JavaScript standard in modern TypeScript. Older projects (Angular, NestJS) may use the legacy experimentalDecorators option.

Common mistakes

Mistake Effect Fix
Numeric enums without explicit values Reordering members changes stored values Use string values, or a union
Using enums in code run by Node.js type stripping Runtime syntax error Use as const objects or unions
const enum across package boundaries Breaks with tools that compile one file at a time Avoid const enum in libraries

Key takeaways

  • Enums work, but union types and as const objects are simpler and erasable.
  • Turn on erasableSyntaxOnly when your code runs through type-stripping tools.

Try it: Convert a PaymentMethod enum to an as const object with a derived union type, and enable erasableSyntaxOnly to confirm no non-erasable syntax remains.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details