TypeScript Basics & Setup
TypeScript is a superset of JavaScript that adds static typing. It catches errors before your code runs.
What Is TypeScript?
TypeScript extends JavaScript with type annotations checked at compile time. It compiles to plain JavaScript.
// JavaScript - errors appear at runtime
let name = "John";
name = 42; // No error, but breaks later
// TypeScript - errors caught at compile time
let name: string = "John";
name = 42; // Error: Type 'number' is not assignable to type 'string'
Why TypeScript? Catches bugs early, adds autocomplete, and makes code self-documenting.
Installing TypeScript
# Global install
npm install -g typescript
# Or as a dev dependency
npm install --save-dev typescript
Tip: Local installation keeps versions pinned per project.
Compiling TypeScript
The tsc compiler converts .ts files to .js:
tsc app.ts # Compile a single file
tsc # Compile using tsconfig.json
tsconfig.json
Configure how TypeScript compiles your project:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Key options: target = JS version output, strict = strict type-checking, outDir = output folder.
@types Packages
JavaScript libraries without built-in types need @types packages:
npm install express @types/express
npm install react react-dom @types/react @types/react-dom
Remember: @types provides type definitions for libraries that don’t ship their own.
Best Practices
- Enable
strictmode in tsconfig - Use
ES2020or later as target - Install
@typesfor third-party libraries - Start simple, add strictness gradually
Common Mistakes
- Not installing
@typespackages - Setting
targettoo old - Running
.tsfiles directly instead of compiling first - Ignoring TypeScript errors
- Using
anyexcessively