Running TypeScript Directly in Node.js with Type Stripping
For years, running TypeScript in Node.js meant a compile step or a loader like ts-node or tsx. Recent Node.js versions can run .ts files directly by stripping the type annotations.
Try it
// greet.ts
interface Person { name: string }
function greet(p: Person): string {
return `Hello, ${p.name}`;
}
console.log(greet({ name: 'Asha' }));
node greet.ts
# Hello, Asha
Type stripping is enabled by default from Node.js 23.6 and 22.18. On earlier 22.x versions, add the --experimental-strip-types flag.
What it does and doesn't do
- It removes types; it does not type-check. Run
tsc --noEmitin your editor and CI for that. - Only "erasable" syntax works: syntax that disappears when types are removed.
enum,namespacewith code, and constructor parameter properties need real code generation and are not supported by plain stripping.- It ignores
tsconfig.jsonpath aliases.
Make the compiler enforce the rules
{
"compilerOptions": {
"noEmit": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"module": "nodenext",
"target": "esnext"
}
}
erasableSyntaxOnlyreports enums and other non-erasable syntax.verbatimModuleSyntaxforcesimport typefor type-only imports, so they're removed cleanly.- Import local files with the
.tsextension:import { db } from './db.ts'.
Replacing enums
const Role = { Admin: 'admin', Member: 'member' } as const;
type Role = (typeof Role)[keyof typeof Role]; // 'admin' | 'member'
Great for scripts, CLIs and small services. For libraries you publish, still compile to JavaScript and ship .d.ts files.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.