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
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.