What is TypeScript?
TypeScript adds static types to JavaScript, catching errors at compile time instead of runtime. It's used by millions of developers for large-scale applications.
// JavaScript — runtime error function greet(name) { return "Hello " + name; } greet(42); // Works, but "Hello 42" — unintended! // TypeScript — compile-time error function greet(name: string): string { return `Hello ${name}`; } greet(42); // ❌ Argument of type 'number' is not assignable to parameter of type 'string'
🔒 Type Safety
Catch type-related bugs before your code runs. No more "undefined is not a function" in production.
💡 Better IDE Support
Autocomplete, refactoring, and navigation work perfectly with typed code.
🔄 Compiles to JS
TypeScript code compiles to plain JavaScript that runs anywhere JS runs — browsers, Node.js, Deno.
Basic Types
TypeScript provides a rich set of primitive and complex types to describe your data.
| Type | Example | Description |
|---|---|---|
| string | "hello" | Text values |
| number | 42, 3.14 | All numbers (integers and floats) |
| boolean | true / false | True/false values |
| array | number[] or Array<string> | List of values |
| tuple | [string, number] | Fixed-length array with specific types |
| enum | enum Color { Red, Green } | Named constants |
| any | let data: any | Opt-out of type checking (use sparingly) |
| unknown | let data: unknown | Type-safe alternative to any |
| void | function log(): void | No return value |
| null / undefined | let x: null | Empty or uninitialized values |
let name: string = "Alice"; let age: number = 30; let isStudent: boolean = false; let hobbies: string[] = ["coding", "reading"]; // Tuple let user: [string, number] = ["Alice", 30]; // Union types let id: string | number = "abc123"; id = 456; // also valid // Type alias type UserId = string | number;
Interfaces
Interfaces define the shape of objects. They're a powerful way to describe contracts in your code.
interface User { id: number; name: string; email?: string; // optional property readonly createdAt: Date; // cannot be changed after creation greet(): string; } const alice: User = { id: 1, name: "Alice", createdAt: new Date(), greet() { return `Hello, I'm ${this.name}`; } }; // Extending interfaces interface Admin extends User { permissions: string[]; isSuperAdmin: boolean; }
Functions & Types
TypeScript lets you define function parameters and return types. You can also create function overloads for multiple call signatures.
// Basic function with types function add(a: number, b: number): number { return a + b; } // Arrow function with type const multiply = (a: number, b: number): number => a * b; // Function type alias type MathOperation = (a: number, b: number) => number; const divide: MathOperation = (x, y) => x / y; // Optional parameters function greet(name: string, title?: string): string { return title ? `Hello, ${title} ${name}` : `Hello, ${name}`; } // Default parameters function createUser(name: string, age: number = 18): User { return { id: 1, name, age }; }
Classes & Access Modifiers
TypeScript adds object-oriented features like public, private, protected, and abstract classes.
class Animal { private secret: string; // only accessible within class protected species: string; // accessible in subclasses public name: string; // accessible everywhere constructor(name: string, species: string) { this.name = name; this.species = species; this.secret = "hidden"; } public makeSound(): void { console.log(`${this.name} makes a sound`); } } class Dog extends Animal { constructor(name: string) { super(name, "canine"); } bark(): void { console.log(`${this.name} barks!`); // console.log(this.secret); ❌ private — error console.log(this.species); // ✅ protected — ok } } const buddy = new Dog("Buddy"); buddy.bark();
Generics
Generics allow you to create reusable components that work with any type while maintaining type safety.
// Generic identity function function identity<T>(arg: T): T { return arg; } const num = identity<number>(42); const str = identity("hello"); // type inference // Generic interface interface Box<T> { value: T; unwrap(): T; } const stringBox: Box<string> = { value: "secret", unwrap() { return this.value; } }; // Generic constraints interface Lengthwise { length: number; } function logLength<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; } logLength("hello"); // works logLength([1, 2, 3]); // works // logLength(42); ❌ number doesn't have .length
Utility Types
TypeScript provides built-in utility types to transform existing types — saving you from writing repetitive code.
interface User { id: number; name: string; email: string; password: string; } // Partial — all properties optional type PartialUser = Partial<User>; // { id?: number; name?: string; ... } // Pick — select specific properties type UserPreview = Pick<User, "id" | "name">; // Omit — exclude properties type PublicUser = Omit<User, "password">; // Readonly — make all properties immutable type ReadonlyUser = Readonly<User>; // Record — create a typed object map type RoleMap = Record<string, string[]>; const permissions: RoleMap = { admin: ["read", "write", "delete"], user: ["read"] };
Configuration (tsconfig.json)
The tsconfig.json file controls how TypeScript compiles your code. Here are the most important options.
{
"compilerOptions": {
/* Language and Environment */
"target": "ES2020", // Output JavaScript version
"module": "commonjs", // Module system
"lib": ["ES2020", "DOM"], // Available libraries
/* Type Checking */
"strict": true, // Enable all strict checks
"noImplicitAny": true, // Error on implicit any
"strictNullChecks": true, // null and undefined are separate
/* Modules */
"rootDir": "./src", // Source directory
"outDir": "./dist", // Output directory
/* Emit */
"sourceMap": true, // Generate source maps for debugging
"removeComments": true // Remove comments from output
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
"strict": true — it enables the most useful type checks and will save you from many bugs.🛠 Project: Type-safe Todo App
Build a simple todo application with TypeScript. This project combines interfaces, types, and DOM manipulation with full type safety.
// Define types interface Todo { id: number; text: string; completed: boolean; createdAt: Date; } type FilterType = "all" | "active" | "completed"; class TodoApp { private todos: Todo[] = []; private nextId: number = 1; private filter: FilterType = "all"; constructor(private storageKey: string) { this.load(); } addTodo(text: string): void { if (!text.trim()) return; const newTodo: Todo = { id: this.nextId++, text: text.trim(), completed: false, createdAt: new Date() }; this.todos.push(newTodo); this.save(); } toggleTodo(id: number): void { const todo = this.todos.find(t => t.id === id); if (todo) { todo.completed = !todo.completed; this.save(); } } deleteTodo(id: number): void { this.todos = this.todos.filter(t => t.id !== id); this.save(); } getFilteredTodos(): Todo[] { switch (this.filter) { case "active": return this.todos.filter(t => !t.completed); case "completed": return this.todos.filter(t => t.completed); default: return [...this.todos]; } } setFilter(filter: FilterType): void { this.filter = filter; } private save(): void { localStorage.setItem(this.storageKey, JSON.stringify(this.todos)); } private load(): void { const data = localStorage.getItem(this.storageKey); if (data) { this.todos = JSON.parse(data); this.nextId = Math.max(...this.todos.map(t => t.id), 0) + 1; } } } // Initialize app const app = new TodoApp("todos");