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
2 min readNode

Run TypeScript in Node without flags

Run a TypeScript script on Node 22.18 or later and use a separate compiler check to catch type errors.

You have a TypeScript script that totals line items, and you want a teammate to run it with the same Node command they use for JavaScript. On the Node 22 line, version 22.18 turns on TypeScript stripping by default.

Save the script and run it

Use an .mts file to make the module format explicit. Save this as total.mts.

type Line = { name: string; cents: number }

const lines: Line[] = [
  { name: 'Tea', cents: 450 },
  { name: 'Toast', cents: 325 },
]

function totalCents(items: Line[]): number {
  return items.reduce((sum, item) => sum + item.cents, 0)
}

console.log(totalCents(lines))

The script adds two integer prices and prints the total in cents. Run it from the directory where you saved it.

node total.mts

Node prints 775. In a project whose nearest package.json has "type": "module", you can save the same script as total.ts and run node total.ts.

Node's TypeScript reference describes which syntax the runtime can erase. Removing the type alias and annotations leaves the array, the function, and the same addition.

Keep the type check

Change the toast price to '325' with quotes and run the script again. You get 450325 because the addition with a string concatenates. Node strips the annotation that says cents is a number, then executes the JavaScript it has left.

For this example, run the compiler in a standalone package with TypeScript installed and no tsconfig.json.

pnpm exec tsc --noEmit total.mts

With the quoted price, TypeScript reports that a string cannot be assigned to a number. Restore 325 and the command exits with no output. If your project config includes the script, run pnpm exec tsc --noEmit -p tsconfig.json to apply the same settings as your editor.

Split the file without changing how it runs

If you move Line into line.mts, export it there and bring it back with import type { Line } from './line.mts'. The type keyword lets Node erase the whole import. For a value you move into another file, include the extension that exists on disk.

Run the script from a clean checkout before putting it in CI. Node ignores tsconfig.json, so a path alias that your editor resolves can still fail at runtime. An enum with runtime values also requires transformation, so the default strip-only mode rejects it. If the script only needs a fixed set of values, try an object or string union and keep the plain Node command.