Enums — what they compile to, and the union that replaces them¶
Level: 201 · for TypeScript users who meet enums in existing code
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A numeric enum compiles to an object keyed both ways, so Object.keys of a two-member enum gives four keys, 0, 1, Up and Down; Node's type stripping refuses an enum, and an as const object plus a union type does the same job.
Keywords: enum, const enum
What the finished page will answer¶
- What JavaScript does
tscwrite forenum Direction { Up, Down }, and why doesObject.keys(Direction)return four keys? - Does a string enum get the reverse mapping too, and what does
Object.keysreturn for it? - What does a
const enumcompile to, and what is left of it at run time? - Why is
move(42)rejected for a numeric enum parameter (TS2345), when older TypeScript accepted any number? - How do an
as constobject and(typeof Direction)[keyof typeof Direction]rebuild an enum from erasable syntax, and what can they not do that an enum can? - What do Node and
tsc --erasableSyntaxOnlysay about anenum, and what does--experimental-transform-typeschange?
Examples it will need¶
-
enums_compiled_output_sh.sh— the reverse-mapping lines tsc emits for a numeric enum, the four keys Node prints for the compiled file, and Node's ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX for the .ts itself -
enums_as_const_alternative_ts.ts— the keys of anas constobject used as an enum, and a function that accepts only its values -
enums_under_erasable_syntax_tserror.ts— tsc's TS1294 for anenumunder the library's tsconfig
See also¶
- Erasable syntax — why Node refuses an enum, with the other refused constructs
- Primitive and literal types — the literal types an enum-like union is built from
keyofandtypeofin types —keyof typeof, the type half of the replacement- Discriminated unions — where a union of literals does an enum's job
- Rust: What an enum is ↗ — a Rust enum is a closed type that
matchmust cover - Rust: An enum instead of a bool ↗ — named states instead of a bare flag, in Rust