Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readNode

Run TypeScript enums on Node 22

Run a TypeScript enum with Node 22’s transform flag, or express the same values with a plain object for a script that uses type stripping.

You add an enum to a script that Node has been running from TypeScript source. The next run fails at the enum declaration. The script now needs a JavaScript value at runtime, and stripping annotations gives Node no such value to load.

Transform the enum on Node 22

Save this as status.mts. The final line needs the string stored in Delivery.Sent.

enum Delivery {
  Queued = "queued",
  Sent = "sent",
}

const state: Delivery = Delivery.Sent;
console.log(state);

With default type stripping on Node 22.18, node status.mts reports ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.

Node 22.7 added an experimental transform flag. Use a Node 22 release at or above that version for this command.

node --experimental-transform-types status.mts

The command prints sent. The transform supplies the runtime enum object that the last line reads.

The flag handles syntax that needs JavaScript emitted, such as the enum above. Keep your type check separate. Use tsc --noEmit to check whether assignments satisfy their annotations.

Use a JavaScript value when it fits

If the script needs two string constants and a type for their possible values, make the runtime object explicit. Save this variant as erasable.mts.

const Delivery = {
  Queued: "queued",
  Sent: "sent",
} as const;

type Delivery = (typeof Delivery)[keyof typeof Delivery];
const state: Delivery = Delivery.Sent;
console.log(state);

Run node erasable.mts on Node 22.18 or later in the 22.x line, where stripping is on by default. It prints sent because stripping leaves the object literal intact.

The object's value type is the union "queued" | "sent". That suits this example. Check how callers use an existing enum before making the substitution. A numeric enum can expose a reverse lookup such as Status[0], and the object above implements no such lookup. If callers need that behavior, leave the enum in place and use a TypeScript build that emits it.