TypeScript
TypeScript is a superset of JavaScript developed by Microsoft that adds static typing and modern language features to improve code quality, maintainability, and scalability. This means all valid JavaScript code is also valid TypeScript code, while TypeScript provides additional development tooling.
1. Why Use TypeScript?
JavaScript is flexible and dynamic, but that flexibility can lead to errors that are difficult to catch. TypeScript helps prevent them before executing code through static typing and editor tooling.
Key Advantages:
- Static typing (prevents common type errors).
- Autocompletion and editor support in VS Code.
- Compile-time error detection.
- Modern JavaScript features enabled across browser environments.
- Maintainable and readable codebase.
Example Issue in JavaScript:
function add(a, b) {
return a + b;
}
console.log(add(5, "10")); // "510" instead of 15
TypeScript Solution:
function add(a: number, b: number): number {
return a + b;
}
// console.log(add(5, "10")); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
console.log(add(5, 10)); // 15
2. Basic Setup and Installation
2.1 Global Installation
Requires Node.js and npm installed.
npm install -g typescript
Verify installation:
tsc -v
2.2 Initialize a TypeScript Project
mkdir ts-project
cd ts-project
npm init -y
npm install typescript --save-dev
Generate the tsconfig.json configuration file:
npx tsc --init
Key compiler settings in tsconfig.json:
{
"compilerOptions": {
"target": "es6", // Target JS version
"module": "commonjs", // Module resolution system
"outDir": "./dist", // Output folder
"rootDir": "./src", // Source code folder
"strict": true, // Enable strict type checks
"esModuleInterop": true // Module compatibility
}
}
Recommended folder structure:
ts-project/
├── src/
│ └── index.ts
├── dist/
├── package.json
└── tsconfig.json
2.3 Compile and Run
To compile:
npx tsc
To run:
node dist/index.js
Or using ts-node directly:
npm install -D ts-node
npx ts-node src/index.ts
3. Basic Types in TypeScript
TypeScript adds explicit types:
let name: string = "Kevin";
let age: number = 25;
let active: boolean = true;
let unassigned: undefined = undefined;
let empty: null = null;
let flexible: any = "Hello"; // Avoid when possible
Arrays:
let numbers: number[] = [1, 2, 3];
let letters: Array<string> = ["a", "b", "c"];
Tuples:
let person: [string, number] = ["Kevin", 25];
Enums:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let favColor: Color = Color.Green;
console.log(favColor); // "GREEN"
Union Types:
let id: string | number;
id = "ABC123";
id = 42;
Type Aliases:
type ID = string | number;
let userID: ID = 101;
4. Functions in TypeScript
Typing parameters and return values:
function greet(name: string): string {
return `Hello, ${name}`;
}
console.log(greet("Kevin"));
Optional and default parameters:
function multiply(a: number, b: number = 2, message?: string): number {
if (message) console.log(message);
return a * b;
}
console.log(multiply(3));
console.log(multiply(3, 4, "Calculating..."));
5. Interfaces and Objects
Interfaces define the shape of an object:
interface User {
id: number;
name: string;
active?: boolean; // optional
}
let user1: User = {
id: 1,
name: "Kevin"
};
6. Classes in TypeScript
class Person {
private name: string;
protected age: number;
public active: boolean;
constructor(name: string, age: number, active: boolean) {
this.name = name;
this.age = age;
this.active = active;
}
greet(): string {
return `Hello, I am ${this.name}`;
}
}
const p1 = new Person("Kevin", 25, true);
console.log(p1.greet());
7. Advanced Types: Generics and Intersections
Generics:
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("Hello"));
console.log(identity<number>(123));
Intersection Types:
interface A { a: string; }
interface B { b: number; }
type AB = A & B;
let obj: AB = { a: "Hello", b: 42 };
8. Interface vs. Type Alias
- Interfaces: Designed primarily to describe object shapes and contracts. Can be extended or merged.
- Type Aliases: Flexible declarations that support union types, primitive aliases, and tuples.