How to Set Up TypeScript in a Project
Advertisement
Ad
Setting Up TypeScript from Scratch
This guide walks you through adding TypeScript to a new or existing Node.js project in under 5 minutes.
Step 1: Install TypeScript
npm init -y
npm install --save-dev typescript @types/node
Step 2: Create tsconfig.json
npx tsc --init
Then set these sensible defaults:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
Step 3: Write Some TypeScript
// src/index.ts
const greet = (name: string): string => `Hello ${name}`;
console.log(greet("World"));
Step 4: Compile & Run
npx tsc # compiles src → dist
node dist/index.js
Step 5: Add Handy Scripts
// package.json
"scripts": {
"build": "tsc",
"dev": "tsc --watch"
}
Bonus: Run TS Directly with tsx
npm install --save-dev tsx
npx tsx src/index.ts # no separate compile step
FAQs
What does "strict": true do?
It enables all strict type-checking options (no implicit any, null checks, etc.). Always keep it on for new projects.
Do I commit the dist folder?
No — add dist/ to .gitignore and build during deployment. See more how-to guides.
