Generics in TypeScript
Mastering TypeScript Generics: generic functions, interfaces, type constraints (T extends object), default generic types, and real-world API wrappers.
Generics in TypeScript
Generics allow you to write reusable, flexible functions, classes, and interfaces that work with a variety of data types while preserving full compile-time type safety.
1. Generic Functions
Instead of losing type information with any, a generic type variable <T> captures the exact type passed by the caller:
// Generic identity function:
function identity<T>(arg: T): T {
return arg;
}
const num = identity(42); // Type inferred as: number
const str = identity("OpenDev"); // Type inferred as: string2. Generic Interfaces & API Wrappers
A universal API response envelope:
interface ApiResponse<TData> {
status: "success" | "error";
statusCode: number;
data: TData;
error?: string;
}
interface User {
id: string;
name: string;
}
// Typed fetch wrapper:
async function apiGet<T>(url: string): Promise<ApiResponse<T>> {
const res = await fetch(url);
return await res.json();
}
// Usage:
const response = await apiGet<User>("/api/me");
console.log(response.data.name); // Fully typed as string!3. Generic Constraints (extends)
Restrict generic type parameters to match a required minimum structure:
interface HasId {
id: string | number;
}
// T MUST have an 'id' property:
function printId<T extends HasId>(item: T): void {
console.log("Entity ID:", item.id);
}
printId({ id: 101, title: "Doc" }); // β
Valid
// printId({ name: "Alex" }); // β Error: Property 'id' is missingRelated Topics
Interfaces vs. Type Aliases in TypeScript
Understanding interfaces in TypeScript: declaration merging, extending interfaces (extends), implementing in classes, and choosing between interface and type.
TypeScript Utility Types (Partial, Pick, Omit, Record)
Mastering built-in TypeScript utility types: Partial, Required, Readonly, Record, Pick, Omit, Exclude, Extract, NonNullable, ReturnType, and Awaited.