Skip to content
jshacks.dev
TypeScript

Use a type-safe enum with a const object

Replace a TypeScript enum with an as const object and a derived union type, which Node.js 24 runs through type stripping with no build step.

2 min read
Summarize in AI

You want a fixed set of named values, the job an enum does, in TypeScript that Node.js 24 runs directly. Type stripping refuses an enum, because an enum is not just a type: it compiles to an object. A plain object marked as const gives you the same names and a union type, with nothing to compile.

TypeScript
const Status = {
  Draft: 'draft',
  Published: 'published',
  Archived: 'archived',
} as const;

type Status = (typeof Status)[keyof typeof Status];

function label(status: Status): string {
  return status === Status.Published ? 'Live' : 'Hidden';
}

console.log(label(Status.Published));
console.log(label('archived'));
console.log(Object.values(Status));
Text
Live
Hidden
[ 'draft', 'published', 'archived' ]

as const makes every property readonly and keeps each value as its literal type, so Status.Published has the type 'published' rather than string. The second line reads the values back out as a union: keyof typeof Status is the three keys, and indexing the object with them gives 'draft' | 'published' | 'archived'. Naming the type the same as the object works because TypeScript keeps types and values in separate namespaces. A plain string literal is accepted too, which is why label('archived') compiles, something a string enum would reject. Node.js only erases the annotations, as the Node.js type stripping documentation describes, so what runs is the object you wrote.

Run the same file with an enum and Node.js 24 stops with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. TypeScript 5.8 added erasableSyntaxOnly to catch that in the editor. Keep a real enum when the code is compiled by tsc anyway and you want reverse mapping from a numeric value back to its name.

Taggednode 24
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.