Setting Up TypeScript
Setting up TypeScript is straightforward with Node.js and npm.
Installation:
bash
# Install globally
npm install -g typescript
# Or per project (recommended)
npm install --save-dev typescriptInitialize a Project:
bash
# Create tsconfig.json
tsc --inittsconfig.json Options: Key options to know:
- target: JavaScript version to compile to (ES2020, ESNext)
- module: Module system (commonjs, ESNext)
- strict: Enable all strict type checking
- outDir: Output directory for compiled JS
Compiling:
bash
# Compile a single file
tsc file.ts
# Compile entire project
tsc
# Watch mode - recompile on changes
tsc --watchRunning TypeScript:
- ts-node: Run TypeScript directly
- Build tools: Vite, webpack, esbuild
Code Examples
tsconfig.json Examplejson
{
"compilerOptions": {
// JavaScript version to compile to
"target": "ES2020",
// Module system
"module": "ESNext",
// Enable all strict type checking
"strict": true,
// Output directory
"outDir": "./dist",
// Source directory
"rootDir": "./src",
// Generate source maps for debugging
"sourceMap": true,
// Allow importing .json files
"resolveJsonModule": true,
// Ensure imports are consistent
"esModuleInterop": true,
// Skip type checking of declaration files
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}The tsconfig.json file configures how TypeScript compiles your code. Start with strict mode enabled for best type safety.
Quick Quiz
1. What command initializes a TypeScript project?
Was this lesson helpful?