TypeScript
Node.js Native Type Stripping
Section titled “Node.js Native Type Stripping”Newer versions of Node.js can run TypeScript files directly via native type stripping. On modern versions of Node, type stripping is stable and enabled by default. For older versions of Node, use the --experimental-strip-types flag. This feature has not been backported to Node 20.
| State | 20 | 22 | 24 |
|---|---|---|---|
| Experimental | n/a | 22.6 | 24.0 |
| Stable | n/a | 22.18 | 24.3 |
You also need --extension ts so Mocha discovers .ts files when scanning directories (the default extensions are .js, .cjs, .mjs).
Note that this does not perform type-checking, it only strips types to allow you to easily run your tests. We recommend using another tool to get the benefits of type-checking.
Quick Start
Section titled “Quick Start”You can run Mocha against ts files matching your spec pattern either by specifying --extension:
mocha --extension tsOr in a configuration file such as .mocharc.js:
export default { extension: ["js", "ts"], spec: "test/**/*.ts",};Older Node Versions (22.6 through 22.17)
Section titled “Older Node Versions (22.6 through 22.17)”Add --node-option experimental-strip-types:
mocha --node-option experimental-strip-types --extension tsOr in .mocharc.js:
export default { "node-option": ["strip-types"] "extension": ["js", "ts"] "spec": ["test/**/*.ts"]}Hello World Example
Section titled “Hello World Example”The example below uses ESM import syntax. It is a minimal working example that does not include everything for IDE support. For IDE integration, see the mocha-examples TypeScript package.
Given a source file src/add.ts:
export function add(a: number, b: number) { return a + b;}And a test file src/add.test.ts:
import assert from "node:assert/strict";import { add } from "./add.ts";
describe("add", function () { it("should add two numbers", function () { assert.strictEqual(add(1, 2), 3); });});Run with:
npx mocha --extension ts src/add.test.tsOther Approaches
Section titled “Other Approaches”For setups that require TypeScript features beyond type stripping (such as enum, namespace, or path aliases), you can use a register-style loader like tsx via --require:
mocha --require ts-node/register --extension tsSee the mocha-examples TypeScript package for complete working examples with different configurations.