Table of Contents
- Prerequisites
- Step 1: Install Node.js and npm
- Step 2: Initialize a Project
- Step 3: Install TypeScript
- Step 4: Configure TypeScript with
tsconfig.json - Step 5: Set Up a Build Process
- Step 6: Code Editor Setup (VS Code)
- Step 7: Create and Run a Sample TypeScript File
- Step 8: Debugging TypeScript
- Optional Tools: Linters, Formatters, and Package Managers
- Troubleshooting Common Issues
- Conclusion
- References
Prerequisites
Before starting, ensure you have:
- A basic understanding of JavaScript.
- A computer running Windows, macOS, or Linux.
- Internet access to download tools.
Step 1: Install Node.js and npm
TypeScript compiles to JavaScript, which runs on Node.js. We’ll use npm (Node Package Manager) to install TypeScript and manage dependencies.
Why Node.js and npm?
- Node.js provides a runtime for executing JavaScript outside the browser.
- npm (included with Node.js) is the default package manager for installing libraries like TypeScript.
Installation Steps:
- Visit the Node.js official website.
- Download the LTS (Long-Term Support) version (recommended for stability).
- Run the installer and follow the prompts (accept defaults for most users).
Verify Installation:
Open a terminal (Command Prompt, PowerShell, or Terminal) and run:
node -v # Should output a version like v20.10.0
npm -v # Should output a version like 10.2.3
If you see errors, restart your terminal or re-install Node.js. For advanced users, consider Node Version Manager (nvm) to manage multiple Node.js versions.
Step 2: Initialize a Project
Next, create a project folder and initialize it with npm to manage dependencies and scripts.
Steps:
-
Create a project folder (e.g.,
typescript-starter) and navigate into it:mkdir typescript-starter cd typescript-starter -
Initialize the project with
npm init:npm init -yThe
-yflag skips prompts and uses default values. This creates apackage.jsonfile, which tracks dependencies and scripts.
What’s in package.json?
name: Project name (e.g.,typescript-starter).version: Project version (default:1.0.0).scripts: Custom commands (we’ll add build/run scripts here later).dependencies: Production dependencies (libraries your app needs to run).devDependencies: Development-only tools (e.g., TypeScript, linters).
Step 3: Install TypeScript
TypeScript is typically installed as a dev dependency (since it’s only needed for development, not runtime).
Install TypeScript Locally:
Run this command in your project folder:
npm install --save-dev typescript
--save-devadds TypeScript todevDependenciesinpackage.json.
Verify Installation:
Check the installed TypeScript version with:
npx tsc --version
You should see output like Version 5.2.2.
Note:
npxruns the local TypeScript compiler (tsc) without globally installing it. Avoid global installs (npm install -g typescript) unless necessary, as project-specific versions are more reliable.
Step 4: Configure TypeScript with tsconfig.json
The tsconfig.json file tells the TypeScript compiler (tsc) how to transpile your TypeScript code to JavaScript. Let’s generate and customize it.
Generate tsconfig.json:
Run:
npx tsc --init
This creates a default tsconfig.json with hundreds of commented options. We’ll focus on key settings.
Key Configuration Options:
Open tsconfig.json in your editor and update these settings (remove comments for clarity):
{
"compilerOptions": {
"target": "ES2020", // Output JavaScript version (ES5, ES6, ES2020, etc.)
"module": "CommonJS", // Module system (CommonJS for Node.js, ESNext for browsers)
"outDir": "./dist", // Where to output compiled JS files (e.g., ./dist)
"rootDir": "./src", // Where your TypeScript source files live (e.g., ./src)
"strict": true, // Enable all strict type-checking options (RECOMMENDED)
"esModuleInterop": true, // Fixes interoperability issues between CommonJS and ES modules
"skipLibCheck": true, // Skip type-checking of .d.ts files (faster builds)
"forceConsistentCasingInFileNames": true, // Avoids case-sensitivity bugs
"sourceMap": true // Generate source maps (for debugging TS in browsers/Node.js)
},
"include": ["./src/**/*"], // Which TS files to compile (all in ./src)
"exclude": ["node_modules"] // Ignore node_modules (no need to compile dependencies)
}
Explanation of Key Options:
target: Determines JS features (e.g.,ES2020supportsBigIntand optional chaining).module:CommonJSis Node.js’s default; useESNextif building for modern browsers with a bundler (Webpack, Vite).outDir: Keeps compiled JS separate from source TS (cleaner project structure).rootDir: Ensurestsconly compiles files in./src(avoids accidental compilation of test files).strict: Enables critical checks likenoImplicitAny(prevents untyped variables) andstrictNullChecks(avoidsnull/undefinedbugs).sourceMap: Generates.mapfiles to map compiled JS back to TS, enabling debugging.
Step 5: Set Up a Build Process
Add npm scripts to simplify compiling TypeScript. Open package.json and update the scripts section:
"scripts": {
"build": "tsc", // Compile TS to JS once
"build:watch": "tsc --watch" // Auto-recompile when TS files change
}
How to Use:
- Run
npm run buildto compile all TS files in./srcto./dist. - Run
npm run build:watchto keep the compiler running; it will recompile whenever you save a TS file (great for development).
Step 6: Code Editor Setup (VS Code)
Visual Studio Code (VS Code) is the most popular editor for TypeScript, thanks to its built-in TypeScript support, IntelliSense, and debugging tools.
Install VS Code:
Download from the VS Code website.
Essential Setup:
-
Open Your Project: Launch VS Code →
File > Open Folder→ Select yourtypescript-starterfolder. -
TypeScript Extension: VS Code has built-in TypeScript support, but ensure it’s enabled:
- Go to Extensions (
Ctrl+Shift+XorCmd+Shift+X). - Search for
TypeScript and JavaScript Language Features(should be pre-installed).
- Go to Extensions (
-
Auto-Compile on Save:
- Go to
File > Preferences > Settings(Ctrl+,orCmd+,). - Search for
files: auto saveand set toonFocusChange(optional but helpful). - To auto-run
tsc --watch, open a terminal in VS Code (Ctrl+`orCmd+\``) and runnpm run build:watch`.
- Go to
-
Formatting: Enable auto-formatting with Prettier (see Optional Tools).
Step 7: Create and Run a Sample TypeScript File
Let’s test your setup with a simple TypeScript script.
1. Create a Source Folder:
First, create the src directory (matching rootDir in tsconfig.json):
mkdir src
2. Write a TypeScript File:
Create src/index.ts with this code:
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
const user = "TypeScript Developer";
const message = greet(user);
console.log(message); // Output: Hello, TypeScript Developer!
name: stringenforces thatgreetonly accepts string inputs.: stringafter the function declares the return type.
3. Compile and Run:
- Run
npm run buildto compilesrc/index.tstodist/index.js. - Run the JS file with Node.js:
You’ll see:node dist/index.jsHello, TypeScript Developer!
Step 8: Debugging TypeScript
Debugging TypeScript directly (without reading compiled JS) is possible with source maps and VS Code’s debugger.
Configure Debugging:
-
In VS Code, open the Run and Debug tab (
Ctrl+Shift+DorCmd+Shift+D). -
Click “create a launch.json file” → Select “Node.js” as the environment.
-
Replace the default
launch.jsonwith:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug TypeScript",
"runtimeArgs": ["-r", "ts-node/register"], // Run TS directly with ts-node
"args": ["${file}"] // Debug the currently open file
}
]
}
Debug Your Script:
- Install
ts-node(runs TS without pre-compiling):npm install --save-dev ts-node - Open
src/index.ts, set a breakpoint (click the gutter next to a line number). - Press
F5to start debugging. The debugger will pause at your breakpoint, allowing you to inspect variables, step through code, and more.
Optional Tools: Linters, Formatters, and Package Managers
Enhance your workflow with these tools:
ESLint (Linting):
ESLint catches code errors and enforces style rules. For TypeScript, use @typescript-eslint:
npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
Create .eslintrc.js:
module.exports = {
parser: "@typescript-eslint/parser",
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
rules: { /* Custom rules */ }
};
Add a script to package.json:
"lint": "eslint src/**/*.ts"
Prettier (Formatting):
Prettier auto-formats code for consistency. Install:
npm install --save-dev prettier eslint-config-prettier
Create .prettierrc:
{ "singleQuote": true, "semi": true }
Update ESLint to work with Prettier in .eslintrc.js:
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier" // Disables ESLint rules conflicting with Prettier
]
Alternative Package Managers:
- Yarn: Faster than npm. Install with
npm install -g yarn, then useyarn addinstead ofnpm install. - pnpm: More efficient disk usage. Install with
npm install -g pnpm, then usepnpm add.
Troubleshooting Common Issues
”tsc: command not found”
- Ensure TypeScript is installed locally (
npm install --save-dev typescript). - Use
npx tscor npm scripts (npm run build) instead oftscdirectly.
Compilation Errors in tsconfig.json
- Check for typos (e.g.,
"outDir": "./dist"instead of"outDir": "./dist"). - Delete
node_modulesandpackage-lock.json, then runnpm installto reset dependencies.
Debugger Not Hitting Breakpoints
- Ensure
sourceMap: trueintsconfig.json. - Verify
ts-nodeis installed andlaunch.jsonis configured correctly.
Conclusion
You now have a fully functional TypeScript development environment! You’ve installed Node.js, set up a project, configured TypeScript, integrated VS Code, and learned to compile, run, and debug TypeScript code.
Next steps: Explore advanced TypeScript features (generics, interfaces, utility types), experiment with bundlers like Webpack, or build a full project (e.g., a Node.js API or React app with TypeScript).