The problem generics are solving
Say you want a function that wraps any value in an array. Without generics you'd either duplicate the function per type, or fall back to any - and any quietly throws away every bit of type information you had.
// Without generics - loses type information
function wrapInArray(value: any): any[] {
return [value];
}
const result = wrapInArray(42); // TypeScript thinks this is any[]
Your first generic function
Add a type parameter - usually called T by convention - in angle brackets. TypeScript figures out what T should be based on whatever you actually pass in.
function wrapInArray<T>(value: T): T[] {
return [value];
}
const nums = wrapInArray(42); // T is inferred as number → number[]
const strs = wrapInArray("hi"); // T is inferred as string → string[]
Generics in interfaces
They're not just for functions - interfaces use them constantly to describe reusable shapes of data.
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
const res: ApiResponse<{ id: string; name: string }> = {
success: true,
data: { id: "abc", name: "Alice" },
};
Constraining what T can be
Use extends when you need to guarantee a certain property exists, so you can safely use it inside the function.
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength("hello"); // 5
getLength([1, 2, 3]); // 3
getLength(42); // Error: number has no .lengthComments
Loading comments...
Related Articles
Taming Slow MongoDB Aggregation Pipelines in Production
An aggregation pipeline that returns instantly on your 500-document local dataset can crawl once it hits a few million real documents. Here's how to actually find and fix the stage that's costing you.
Read ArticleBuilding a Sliding-Window Rate Limiter for Node.js APIs with Redis
Fixed-window rate limiting looks fine in a demo and then lets through double the traffic right at the window boundary. Here's the sliding-window-counter approach that fixes that, built directly on Redis.
Read ArticleMulti-Tenant Data Isolation: Shared Schema vs Separate Databases
Every multi-tenant SaaS eventually has to answer one question honestly: how do you stop one customer from ever seeing another customer's data? Here's how the three common isolation strategies actually compare in practice.
Read Article