What are Generics?
Generics allow you to write reusable code that works with multiple types.
\\\`typescript
function identity<T>(arg: T): T {
return arg;
}
const num = identity(42); // type: number
const str = identity("hello"); // type: string
\\\`
Generic Constraints
\\\`typescript
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): T {
console.log(arg.length);
return arg;
}
\\\`
Real-World: API Response
\\\`typescript
interface ApiResponse<T> {
data: T;
status: number;
}
async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
const response = await fetch(url);
return response.json();
}
\\\`
Key Takeaway: Generics = Type Safety + Reusability ๐ฏ