TypeScript Enums vs Union Types: Should You Use Enums?

Enums, const enums, parameter properties and namespaces emit runtime code. Why many teams prefer string unions and erasable syntax.

In this chapter

TypeScript-only features: enums and friends

More on Everyday types

Keep learning

Overview

chapters · everyday types TypeScript-only features: enums and friends Most TypeScript vanishes when compiled. A few features generate JavaScript. Know which, and why teams avoid them. Compiling turns your .ts file into a .js file. Most TypeScript is simply deleted in that step. To emit means "to write out JavaScript". The features in this chapter emit extra JavaScript you never typed.

1. The problem: the right string, rejected

Both versions limit a payment method to 'CARD' or 'CASH'. An enum is a named list of fixed values. A literal type is a type that allows exactly one value, like 'CARD'. A union (A | B) means "A or B". string enum Argument of type '"CARD"' is not assignable to parameter of type 'PayMethod'. Line 8 fails even though PayMethod.Card is the text 'CARD'. A string enum accepts only its own members, not a plain string with the same text. Data from an API or a form is a plain string, so every caller must import the enum. union of string literals Argument of type '"CHEQUE"' is not assignable to parameter of type 'PayMethod'. Line 5 works: 'CARD' is one of the two allowed strings. Line 6 fails: 'CHEQUE' is not. Same safety, plain strings work, and no JavaScript is emitted.

2. Erased vs emitted

types + JavaScript strip types delete annotations, interfaces, generics Erasable syntax: deleting it leaves valid JavaScript with the same behavior. Annotations, interfaces, type aliases Deleted. Zero runtime cost. Generics, as, satisfies, declare emits code Becomes an object, or gets inlined. namespace, parameter properties Quick glosses: a generic is a type with a placeholder, like Array<T>. as tells TypeScript "treat this value as type X". satisfies checks a value against a type. declare describes something that exists elsewhere. All four are pure type information, so they are deleted.

3. Numeric enums: a two-way object

you write (.ts) tsc emits (.js) With no values given, members are numbered 0, 1, 2. The object stores each member both ways: name → number and number → name. The number → name direction is called a reverse mapping. value at runtime reverse mapping six keys, not three: 3 names + 3 reverse-mapping numbers

Numeric enums still accept any number variable

Type '7' is not assignable to type 'OrderStatus'. Line 3 fails: the members are 0, 1 and 2, and the literal 7 is none of them. Line 5 is allowed: fromApi is just "some number", which could be 0, 1 or 2. TypeScript lets it through without checking, so a bad 7 slips in. What is n at runtime?

4. String enums: no reverse map, matched by name

A string enum gives each member a text value. It has no reverse mapping. Here two enums hold the very same value, 'CARD'. Type 'LegacyPay' is not assignable to type 'PayMethod'. Line 4 fails even though both values are 'CARD'. An enum type only accepts members of that same enum. "Not assignable to" means "doesn't fit into". Nominal (matched by name): two enums with the same values do not mix. A plain 'CARD' is rejected. Everything else Structural (matched by shape): if the fields and values fit, it is accepted. See the structural typing chapter.

5. const enums and isolatedModules

you write tsc emits The value "M" is inlined (pasted in place of Size.M). To do that, the compiler must open the file where Size is defined. A .d.ts file (a declaration file) holds only types, no code. Things declared there are called ambient. isolatedModules is a setting that says "each file must compile on its own, without reading other files". Line 6 fails: to inline Size.M, the compiler must read sizes.d.ts, but isolatedModules forbids that. The setting exists because esbuild, Babel, swc and Vite compile one file at a time. They cannot look up another file’s enum to inline it.

6. Namespaces and parameter properties emit code too

namespace (.ts) emitted (.js) parameter properties (.ts) Lines 2–3 and 5–6 appear even though you never wrote them. public/private on a constructor parameter means "also make this a field".

7. erasableSyntaxOnly and Node type stripping

Type stripping means running a .ts file by blanking out the types, without type-checking or compiling. It only works if nothing needs to be emitted. node app.ts recent Node runs .ts directly replace types with spaces no type-check, no emit enum / namespace / param props cannot be stripped: error Node 22.18+ and 23.6+ strip types by default. Unsupported syntax throws ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.

The compiler flag that matches

This syntax is not allowed when 'erasableSyntaxOnly' is enabled.

8. What to use instead

Model a status as string enum Argument of type '"paid"' is not assignable to parameter of type 'Status'. Emits an object. Line 7 fails: 'paid' is a plain string, and the enum accepts only Status.Paid. Not erasable. union of literals Argument of type '"lost"' is not assignable to parameter of type 'Status'. Zero runtime code. Plain strings work. Line 4 fails because 'lost' is not one of the two allowed strings. Autocomplete still lists the options. "pending" | "paid" Named constants and a union type, from one source. Plain JavaScript object.

Building the Status type from the object

typeof Status: the type of that object keyof …: the union of its key names 'Pending' | 'Paid' T[K]: look up the value type at those keys 'pending' | 'paid' string enum literal union Accepts plain strings Named constants (Status.Paid) Loop over values at runtime Erasable / type-strip safe

Remember

Numeric enums have reverse mappings and accept any number variable. String enums are nominal: plain strings and look-alike enums are rejected. erasableSyntaxOnly keeps code runnable by Node’s type stripping. ! Cheat code → Go deeper: unions and literal types, namespaces, tsconfig that catches bugs, interview: enum or union?.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.