TypeScript Notes
Interfaces, generics, utility types, and strict mode configurations.
TypeScript Complete Notes
1. Type System
TypeScript ka sabse bada feature hai Static Type System.
JavaScript dynamically typed hai:
let name = "Sannu";
name = 10; // Valid hai.
TypeScript me:
let name: string = "Sannu";
name = 10; // Error.
Benefits:
- Compile time error detection
- Better IntelliSense
- Safer refactoring
- Self-documenting code
Primitive Types:
let age: number = 25;
let username: string = "Sannu";
let active: boolean = true;
let data: null = null;
let value: undefined = undefined;
2. Interfaces
Interface object ka structure define karta hai.
interface User {
id: number;
name: string;
email: string;
}
// Use:
const user: User = {
id: 1,
name: "Sannu",
email: "test@gmail.com"
};
Benefits:
- Consistent object structure
- Type checking
- Reusability
Optional Properties:
interface User {
id: number;
name?: string; // name optional hai
}
Readonly:
interface User {
readonly id: number; // Change nahi kar sakte
}
3. Types
Interface ki tarah custom type create karta hai.
type User = {
id: number;
name: string;
};
Union Type:
type Status = "pending" | "success" | "failed"; // Only 3 values allowed.
Intersection Type:
type Admin = { role: string; };
type User = { name: string; };
type AdminUser = User & Admin;
// Result: { name: string; role: string; }
Interface vs Type (Interview Point):
- Interface: Extend easily, Declaration merging supported.
- Type: Union, Intersection, More flexible.
4. Generics
Reusable type-safe code likhne ke liye.
Generic:
function identity<T>(value: T): T {
return value;
}
identity<string>("Hello");
identity<number>(10);
Generic Array & Interface:
const items: Array<string> = ["A", "B", "C"]; // Equivalent to string[]
interface ApiResponse<T> {
success: boolean;
data: T;
}
5. Utility Types
TypeScript built-in helper types.
- Partial: Sab properties optional bana deta hai.
Partial<User> - Required: Sab required bana deta hai.
Required<User> - Readonly:
Readonly<User> - Pick: Kuch fields select karo.
Pick<User, "id" | "name"> - Omit: Fields remove karo.
Omit<User, "id"> - Record:
Record<string, User>
6. Declaration Merging
TypeScript interfaces merge ho sakte hain.
interface User { name: string; }
interface User { age: number; }
// Automatically merges to: { name: string; age: number; }
(Interview Favorite: Type alias merge nahi hota, Interface merge hota hai.)
7. Decorators
Class ko modify karne ke liye (Enable experimentalDecorators: true).
function Logger(target: Function) {
console.log(target);
}
@Logger
class User {}
Common Uses: Dependency Injection, Logging, Validation, Metadata.
8. Type Narrowing
Type ko runtime checks se narrow karna.
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase()); // TS samajh gaya value string hai
}
}
// instanceof and in Operator
if (user instanceof User) {}
if ("name" in user) {}
9. Advanced Type Patterns (Senior-level)
Conditional Types:
type IsString<T> = T extends string ? true : false;
Infer Keyword: (Type extract karne ke liye)
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
Mapped Types: (Object properties transform karte hain)
type ReadonlyUser = { readonly [K in keyof User]: User[K]; };
keyof: (Object keys nikalta hai)
type UserKeys = keyof User; // "id" | "name"
Indexed Access Types:
type UserName = User["name"]; // string