Generics Basics
Purpose: write reusable, type-safe code. Benefit: flexibility without losing safety.
David Miller
January 4, 2026
1.0k20
Generics let you write code that works with many types safely.
Simple generic function
function identity<T>(value: T): T {
return value;
}
identity<number>(10);
identity<string>("hello");
Generic array function
function first<T>(arr: T[]): T {
return arr[0];
}
first([1, 2, 3]);
first(["a", "b"]);
Generic interface
interface ApiResponse<T> {
data: T;
status: number;
}
const res: ApiResponse<string> = {
data: "ok",
status: 200,
};
Graph: generics idea
flowchart LR
A[Generic T] --> B[Used with number]
A --> C[Used with string]
A --> D[Used with objects]
Remember
- generics = reusable + safe
- avoid repeating same logic for many types
#TypeScript#Beginner#Generics