Complete TypeScript Tutorial

By Shri Chand Thapa Β· Published July 23, 2026

Comprehensive TypeScript guide from basics to advanced topics, explained with real-world examples covering types, functions, OOP, and more.

  • typescript
  • hinglish
  • programming-tutorial
  • oop
  • type-system
32 cells1 experiment4 views0 forks

Inside this notebook

# πŸ“˜ Complete TypeScript Tutorial β€” Basics se Advanced tak (Hinglish) > **Yeh notebook ek comprehensive TypeScript guide hai** β€” bilkul zero se lekar advanced topics tak. > Har concept ko Hinglish (Hindi + English mix) mein explain kiya gaya hai, real-world examples ke saath. ## πŸ“‹ Table of Contents | # | Chapter | Topics | |---|---------|--------| | 1 | **TypeScript Basics** | Types, Annotations, Inference, Arrays, Tuples, Enums, Unions, Intersections, Literals | | 2 | **Functions** | Function Types, Overloads, Optional/Default/Rest Params, `this`, Arrow Functions | | 3 | **Objects & Interfaces** | Object Types, Interfaces, Index Signatures, Extends, Type vs Interface | | 4 | **Classes & OOP** | Access Modifiers, Abstract Classes, Implements, Static, Parameter Properties | | 5 | **Generics Deep Dive** | Constraints, Defaults, Multiple Params, Inference, Generic Classes/Interfaces | | 6 | **Advanced Types** | Conditional, Mapped, Template Literal, `infer`, `keyof`, `typeof`, Indexed Access | | 7 | **Type Guards & Narrowing** | `typeof`, `instanceof`, `in`, Custom Guards, Discriminated Unions, Exhaustive Checks | | 8 | **Utility Types** | `Partial`, `Required`, `Pick`, `Omit`, `Record`, `Exclude`, `Extract`, `ReturnType`, etc. | | 9 | **Modules & Namespaces** | ES Modules, Import/Export, Namespaces, Declaration Files (`.d.ts`) | | 10 | **Decorators** | Class, Method, Property, Parameter Decorators + Factories | | 11 | **Advanced Patterns** | Recursive Types, Variadic Tuples…

# Chapter 1: TypeScript Basics πŸ—οΈ ## 1.1 TypeScript Kya Hai? (What is TypeScript?) **TypeScript = JavaScript + Static Typing** JavaScript ek dynamically typed language hai β€” matlab variable ka type runtime pe decide hota hai. TypeScript usme **compile-time type checking** add karta hai. ```typescript // ❌ JavaScript β€” yeh error runtime pe aayega (jab app crash ho chuki hogi) function greet(name) { return "Hello, " + name.toUpperCase(); } greet(42); // Runtime: TypeError: name.toUpperCase is not a function // βœ… TypeScript β€” yeh error COMPILE time pe hi pakad lega function greet(name: string): string { return "Hello, " + name.toUpperCase(); } greet(42); // ❌ Compile Error: Argument of type 'number' is not assignable to 'string' ``` ### TypeScript Kyun Use Karein? | Fayda | Explanation | |-------|-------------| | πŸ› **Early Bug Detection** | Errors compile time pe milte hain, production mein nahi | | 🧠 **Better IntelliSense** | VS Code mein autocomplete, refactoring next level | | πŸ“– **Self-Documenting Code** | Types dekh ke samajh aata hai function kya expect karta hai | | πŸ”§ **Safe Refactoring** | Type system bata dega kahan kahan changes karne hain | | 🏒 **Large Teams** | 100+ developers ke saath kaam karna possible hota hai | ### TypeScript Kaise Kaam Karta Hai? ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ .ts File │────▢│ TypeScript │────▢│ .js File β”‚ β”‚ (aapka code)β”‚ β”‚ Compiler (tsc) β”‚ β”‚ (browser/ β”‚ │…

## 1.2 Basic Types (Primitive Types) 🧱 TypeScript mein har variable ko ek **type** assign hota hai. Yeh types compile-time pe check hote hain. ### The Big 3: `string`, `number`, `boolean` ```typescript // string β€” text data let userName: string = "Shri"; let greeting: string = `Hello, ${userName}!`; // template literals bhi kaam karte hain // number β€” integers AUR floating point dono (JS mein alag int/float nahi hota) let age: number = 25; let price: number = 99.99; let hex: number = 0xff; // hexadecimal let binary: number = 0b1010; // binary let octal: number = 0o744; // octal let infinity_: number = Infinity; let notANumber: number = NaN; // haan, NaN bhi 'number' type hai! πŸ˜… // boolean β€” true ya false let isLoggedIn: boolean = true; let hasPermission: boolean = false; ``` ### Special Types ```typescript // any β€” "mujhe type check nahi chahiye" (AVOID karo!) let anything: any = 42; anything = "hello"; // βœ… no error anything = true; // βœ… no error anything.nonExistent(); // βœ… no error (but runtime pe crash!) // ⚠️ 'any' use karna = TypeScript ka fayda khatam. Jab tak possible ho, avoid karo. // unknown β€” "type nahi pata, but safe raho" (any ka SAFE alternative) let data: unknown = fetchSomething(); data.toUpperCase(); // ❌ Error! Pehle type check karo if (typeof data === "string") { data.toUpperCase(); // βœ… Ab safe hai β€” TypeScript ne narrow kar diya } // void β€” "kuch return nahi hoga" function logMessage(msg: string): void { consol…

## 1.3 Type Annotations vs Type Inference 🎯 ### Type Annotation β€” Explicitly type likhna ```typescript // Jab aap KHUD type specify karte ho let name: string = "Shri"; let age: number = 25; let scores: number[] = [90, 85, 92]; // Function parameters mein annotation ZAROORI hai function add(a: number, b: number): number { return a + b; } ``` ### Type Inference β€” TypeScript KHUD guess karta hai ```typescript // TypeScript automatically type infer kar leta hai let city = "Mumbai"; // TypeScript jaanta hai: string let count = 42; // TypeScript jaanta hai: number let isActive = true; // TypeScript jaanta hai: boolean city = 123; // ❌ Error! TypeScript ne infer kiya tha string // Function return type bhi infer hota hai function multiply(a: number, b: number) { return a * b; // TypeScript infer: return type = number } // ⚠️ Lekin hamesha inference pe depend mat karo: let value; // Type: any (koi initial value nahi, TS guess nahi kar sakta) value = "hello"; // Ab bhi any hai! value = 42; // Koi error nahi β€” yeh dangerous hai // βœ… Better: initialize karo ya annotate karo let value2 = "hello"; // Type: string (inferred from initial value) let value3: string; // Type: string (explicit annotation) ``` ### Kab Annotation, Kab Inference? ```typescript // βœ… Inference kaafi hai β€” jab initial value clear ho const name = "Shri"; // obviously string const nums = [1, 2, 3]; // obviously number[] // βœ… Annotat…

## 1.4 Arrays & Tuples πŸ“¦ ### Arrays β€” Same type ke elements ka collection ```typescript // Syntax 1: type[] let numbers: number[] = [1, 2, 3, 4, 5]; let names: string[] = ["Shri", "Ram", "Sita"]; let flags: boolean[] = [true, false, true]; // Syntax 2: Array<type> (Generic syntax β€” Chapter 5 mein detail mein) let scores: Array<number> = [90, 85, 92]; let cities: Array<string> = ["Mumbai", "Delhi", "Bangalore"]; // Mixed array (union type ke saath) let mixed: (string | number)[] = ["age", 25, "name", "Shri"]; // Array methods β€” sab type-safe hain! numbers.push(6); // βœ… number push karo numbers.push("seven"); // ❌ Error! string allowed nahi let first: number = numbers[0]; // βœ… returns number let joined: string = names.join(", "); // βœ… string method // Readonly array β€” modify nahi kar sakte let readOnlyNums: readonly number[] = [1, 2, 3]; readOnlyNums.push(4); // ❌ Error! push allowed nahi readOnlyNums[0] = 10; // ❌ Error! index assignment nahi // Multi-dimensional arrays let matrix: number[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; let cell: number = matrix[1][2]; // 6 ``` ### Tuples β€” Fixed length, fixed types ```typescript // Tuple: exact position pe exact type let user: [string, number, boolean] = ["Shri", 25, true]; let name_: string = user[0]; // "Shri" let age_: number = user[1]; // 25 let active: boolean = user[2]; // true user[0] = "Ram"; // βœ… string assign karo string position pe user[1] = "twenty"; // ❌ Error! number posi…

## 1.5 Enums β€” Named Constants πŸ”’ Enums ek set of related constants ko meaningful names dete hain. ### Numeric Enums (Default) ```typescript // Auto-incrementing (0 se shuru) enum Direction { Up, // 0 Down, // 1 Left, // 2 Right // 3 } let move: Direction = Direction.Up; console.log(move); // 0 console.log(Direction[0]); // "Up" (reverse mapping!) console.log(Direction.Up); // 0 // Custom starting value enum HttpStatus { OK = 200, Created = 201, BadRequest = 400, NotFound = 404, ServerError = 500 } let status: HttpStatus = HttpStatus.NotFound; console.log(status); // 404 ``` ### String Enums (Recommended βœ…) ```typescript // String enums β€” zyada readable aur debuggable enum UserRole { Admin = "ADMIN", Editor = "EDITOR", Viewer = "VIEWER", Guest = "GUEST" } let role: UserRole = UserRole.Admin; console.log(role); // "ADMIN" (actual string value, not a number!) // Function mein use function canDelete(userRole: UserRole): boolean { return userRole === UserRole.Admin || userRole === UserRole.Editor; } canDelete(UserRole.Admin); // true canDelete("ADMIN"); // βœ… String enums mein yeh bhi kaam karta hai canDelete("admin"); // ❌ Error! case-sensitive ``` ### Const Enums (Performance) ```typescript // const enum β€” compile time pe inline ho jata hai (no runtime object) const enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE" } let c…

## 1.6 Union Types β€” "Ya Yeh, Ya Woh" πŸ”€ Union type ka matlab: variable **in types mein se koi ek** ho sakta hai. ```typescript // Basic union let id: string | number; id = "ABC-123"; // βœ… string id = 42; // βœ… number id = true; // ❌ Error! boolean allowed nahi // Function parameter mein union function printId(id: string | number): void { // ⚠️ Sirf COMMON methods use kar sakte ho console.log(id.toString()); // βœ… toString() dono pe hai console.log(id.toUpperCase()); // ❌ Error! number pe toUpperCase nahi // Type narrowing se safe access if (typeof id === "string") { console.log(id.toUpperCase()); // βœ… Ab TypeScript jaanta hai: string } else { console.log(id.toFixed(2)); // βœ… Ab TypeScript jaanta hai: number } } // Union with arrays let list: (string | number)[] = ["age", 25, "name", "Shri"]; // Union with objects type Dog = { bark: () => void; name: string }; type Cat = { meow: () => void; name: string }; function makeSound(pet: Dog | Cat): void { console.log(pet.name); // βœ… 'name' dono mein hai // pet.bark(); // ❌ Error! Cat pe bark nahi if ("bark" in pet) { pet.bark(); // βœ… Narrowed to Dog } else { pet.meow(); // βœ… Narrowed to Cat } } ``` ### Union + Type Aliases ```typescript // Type alias se union ko naam do type StringOrNumber = string | number; type ID = string | number; function findUser(id: ID): void { if (typeof id === "string") { console.log(`Searching…

## 1.8 Literal Types β€” Exact Values 🎯 Literal types ka matlab: variable sirf **ek specific value** hi hold kar sakta hai. ```typescript // String literals let direction: "north" | "south" | "east" | "west"; direction = "north"; // βœ… direction = "up"; // ❌ Error! "up" allowed nahi // Number literals let diceRoll: 1 | 2 | 3 | 4 | 5 | 6; diceRoll = 3; // βœ… diceRoll = 7; // ❌ Error! // Boolean literal let isReady: true = true; // isReady = false; // ❌ Error! sirf true allowed // Practical: function parameters type Alignment = "left" | "center" | "right"; function setAlignment(align: Alignment): void { console.log(`Text aligned: ${align}`); } setAlignment("center"); // βœ… setAlignment("middle"); // ❌ Error! // Literal + Union = powerful pattern type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; function apiCall(method: HttpMethod, url: string): void { console.log(`${method} ${url}`); } apiCall("GET", "/users"); // βœ… apiCall("FETCH", "/users"); // ❌ Error! // const assertion se literal type banta hai const config = { method: "GET", // Type: string (widened) url: "/api/users" }; const configStrict = { method: "GET", // Type: "GET" (literal! β€” const assertion se) url: "/api/users" } as const; // configStrict.method = "POST"; // ❌ Error! readonly + literal ``` ## 1.9 Type Assertions β€” "Mujhe Zyada Pata Hai" 🏷️ Jab aapko TypeScript se zyada information ho, toh type assertion use karo. ```typescript // Syntax 1: 'as' keyw…

# Chapter 2: Functions in TypeScript ⚑ ## 2.1 Function Typing β€” Basics Functions TypeScript mein first-class citizens hain β€” unhe bhi type kiya ja sakta hai. ```typescript // Basic typed function function add(a: number, b: number): number { return a + b; } // Arrow function with types const subtract = (a: number, b: number): number => { return a - b; }; // Return type inference β€” TypeScript khud samajh jata hai const multiply = (a: number, b: number) => a * b; // return type: number (inferred) // ⚠️ Lekin explicit return type BETTER hai (documentation + safety) const divide = (a: number, b: number): number => { if (b === 0) throw new Error("Division by zero!"); return a / b; }; ``` ### Function Type Expressions ```typescript // Function ko ek type do type MathFn = (a: number, b: number) => number; // Ab is type ke saath functions banao const add: MathFn = (a, b) => a + b; // a, b automatically number hain! const sub: MathFn = (a, b) => a - b; const mul: MathFn = (a, b) => a * b; // Function as parameter function calculate(a: number, b: number, operation: MathFn): number { return operation(a, b); } calculate(10, 5, add); // 15 calculate(10, 5, sub); // 5 calculate(10, 5, (x, y) => x ** y); // 100000 β€” inline arrow bhi kaam karta hai // Callback typing function fetchData(url: string, onSuccess: (data: string) => void, onError: (err: Error) => void): void { try { const data = `Response from ${url}`; onSuccess(data); }…

## 2.3 Function Overloads β€” Same Naam, Different Signatures πŸ”„ Jab ek function alag-alag types ke inputs pe alag-alag return types de, toh overloads use karo. ```typescript // Overload signatures (implementation nahi hoti inki) function format(value: string): string; function format(value: number): string; function format(value: boolean): string; // Implementation signature (actual code yahan) function format(value: string | number | boolean): string { if (typeof value === "string") { return value.trim().toUpperCase(); } else if (typeof value === "number") { return value.toFixed(2); } else { return value ? "YES" : "NO"; } } format(" hello "); // "HELLO" format(3.14159); // "3.14" format(true); // "YES" format([1, 2, 3]); // ❌ Error! Overload match nahi hua // Practical example: different return types function getElement(id: string): HTMLElement; function getElement(ids: string[]): HTMLElement[]; function getElement(input: string | string[]): HTMLElement | HTMLElement[] { if (typeof input === "string") { return document.getElementById(input)!; } return input.map(id => document.getElementById(id)!); } const single = getElement("app"); // Type: HTMLElement const multiple = getElement(["a", "b"]); // Type: HTMLElement[] // ⚠️ Bina overloads ke, return type union hota: HTMLElement | HTMLElement[] ``` ### Overloads vs Union Types ```typescript // ❌ Overloads β€” complex, verbose function parse(in…

# Chapter 3: Objects & Interfaces πŸ›οΈ ## 3.1 Object Types β€” Inline Definition ```typescript // Inline object type function printUser(user: { name: string; age: number; email?: string }): void { console.log(`${user.name}, ${user.age}`); if (user.email) { console.log(`Email: ${user.email}`); } } printUser({ name: "Shri", age: 25 }); // βœ… email optional printUser({ name: "Shri", age: 25, email: "s@e.com" }); // βœ… with email printUser({ name: "Shri" }); // ❌ age missing! // Nested objects type Company = { name: string; address: { street: string; city: string; country: string; }; employees: { name: string; role: string; }[]; }; let company: Company = { name: "TechCorp", address: { street: "MG Road", city: "Mumbai", country: "India" }, employees: [ { name: "Shri", role: "Developer" }, { name: "Ram", role: "Designer" } ] }; ``` ## 3.2 Interfaces β€” Object Ka Blueprint πŸ“ Interface ek **contract** hai β€” "agar tumhe yeh type chahiye, toh yeh properties HONI chahiye." ```typescript // Basic interface interface User { id: string; name: string; email: string; age: number; } // Interface ko implement karo const user: User = { id: "u-001", name: "Shri Chand Thapa", email: "shri@example.com", age: 25 }; // ❌ Extra properties allowed nahi (excess property check) const badUser: User = { id:…

## 3.4 Interface Extends β€” Inheritance πŸ”— ```typescript // Base interface interface BaseEntity { id: string; createdAt: Date; updatedAt: Date; } // Extend karo β€” parent ki saari properties mil jaati hain interface User extends BaseEntity { name: string; email: string; } interface Admin extends User { permissions: string[]; superAdmin: boolean; } let admin: Admin = { id: "a-001", createdAt: new Date(), updatedAt: new Date(), name: "Shri", email: "shri@admin.com", permissions: ["read", "write", "delete"], superAdmin: true }; // Multiple inheritance interface HasName { name: string; } interface HasAge { age: number; } interface HasEmail { email: string; } interface Person extends HasName, HasAge, HasEmail { occupation: string; } let person: Person = { name: "Shri", age: 25, email: "shri@example.com", occupation: "Developer" }; ``` ## 3.5 Declaration Merging β€” Interface Ki Superpower 🦸 ```typescript // Same naam ke interfaces AUTOMATICALLY merge ho jaate hain! interface Window { myCustomProp: string; } // Ab Window interface mein myCustomProp bhi hai + original props bhi // window.myCustomProp = "hello"; // βœ… TypeScript allow karega // Practical: Third-party library extend karna interface ExpressRequest { user?: { id: string; role: string }; } // Baad mein aur properties add karo interface ExpressRequest { requestId: string; timestamp: number; } // Ab ExpressRequest mein SAB…

This is a preview. Open the live notebook to see all 32 cells with their charts and full outputs, or fork it into your own Clusy workspace.

Complete TypeScript Tutorial | Clusy