Chapter 7TypeScript~1 min read
Generics
Reusable Type-Safe Code
Generics म्हणजे type चे parameters — function किंवा class define करताना exact type सांगायचं नाही, use करताना सांगायचं. यामुळे एकच function multiple types सोबत काम करू शकतो.
Marathi Analogy
Generic function म्हणजे एक mold जो कोणत्याही shape चं material घेऊ शकतो. मold एकच, पण आत gold, silver, copper — काहीही ओतता येतं!
Generic function
typescript
// Without generics — any वापरावं लागतं (unsafe)
function identity(value: any): any {
return value;
}
// With generics — type safe!
function identity<T>(value: T): T {
return value;
}
// Use करा
const num = identity<number>(42); // type: number
const str = identity<string>("hello"); // type: string
const arr = identity([1, 2, 3]); // inferred: number[]
// Generic array function
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const first = firstElement([10, 20, 30]); // type: number
const name = firstElement(["Pune", "Mumbai"]); // type: stringGeneric interface आणि constraints
typescript
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Use करा
type UserResponse = ApiResponse<{ name: string; email: string }>;
type ListResponse = ApiResponse<string[]>;
// Generic constraint — T ला length property असावं
function logLength<T extends { length: number }>(item: T): void {
console.log(item.length);
}
logLength("hello"); // ✅ string has length
logLength([1, 2, 3]); // ✅ array has length
logLength(42); // ❌ ERROR: number has no length✅ Key Points — लक्षात ठेवा
- ▸<T> — generic type parameter
- ▸T extends Type — constraint लावा
- ▸Generic functions multiple types सोबत काम करतात
- ▸ApiResponse<T> — real-world use case
- ▸React useState<T> internally generic आहे
0/9 chapters पूर्ण