TypeScriptTypeScript18 min read

Generics Basics

Purpose: write reusable, type-safe code. Benefit: flexibility without losing safety.

David Miller
December 21, 2025
0.0k0

Generics let you write code that works with many types safely. ## Simple generic function ```ts function identity<T>(value: T): T { return value; } identity<number>(10); identity<string>("hello"); ``` ## Generic array function ```ts function first<T>(arr: T[]): T { return arr[0]; } first([1, 2, 3]); first(["a", "b"]); ``` ## Generic interface ```ts interface ApiResponse<T> { data: T; status: number; } const res: ApiResponse<string> = { data: "ok", status: 200, }; ``` ## Graph: generics idea ```mermaid 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