Setting Up TypeScript with Node
In this page:
Creating a TypeScript Project
Creating a TypeScript project for Node starts with npm init for the package and npm install --save-dev typescript, which gives you the local tsc compiler your project will use to build.
Example: Creating a TypeScript Project
// npm init -y
// npm install --save-dev typescript
console.log("Project scaffolded with npm init and a local tsc install");
Configuring tsconfig.json
Configuring tsconfig.json — setting options like target, module, and outDir — tells the compiler which JavaScript version to emit and where to place the compiled files relative to your source folder.
Example: Configuring tsconfig.json
// tsconfig.json
// { "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "dist" } }
console.log("tsconfig.json configures target, module, and outDir");
Compiling TypeScript
Running tsc reads your tsconfig.json and compiles every included .ts file into plain .js, catching any type errors along the way and refusing to emit output if noEmitOnError is enabled.
Example: Compiling TypeScript
// tsc
// Reads tsconfig.json, compiles src/*.ts into dist/*.js
console.log("Running tsc compiles .ts files and reports type errors");
Running the Compiled Program
The compiled output is ordinary JavaScript, so running it is just node dist/index.js (or whatever your configured outDir is) — Node itself never runs TypeScript directly, only the JavaScript that TypeScript produces.
Example: Running the Compiled Program
// node dist/index.js
console.log("Node runs the compiled JavaScript output, never .ts directly");
Practical Project Structure
A practical project structure keeps source .ts files in a src/ folder and compiled output in a separate dist/ folder, which keeps generated JavaScript out of version control and out of the way of your source tree.
Example: Practical Project Structure
// src/index.ts -> source files (version controlled)
// dist/index.js -> compiled output (gitignored)
console.log("src/ holds TypeScript source, dist/ holds compiled JavaScript");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: