TypeScriptTypeScript20 min read

TypeScript Generics Intro

Learn generics to write reusable, type-safe functions and classes without losing flexibility.

David Miller
December 21, 2025
0.0k0

Generics let you write code that works with many types, but still stays type-safe. ## Why generics? Without generics: ```ts function identity(value: any): any { return value; } ``` You lose type safety. With generics: ```ts function identity<T>(value: T): T { return value; } const a = identity<number>(10); const b = identity("hello"); ``` TypeScript remembers the type. ## Generic with arrays ```ts function first<T>(arr: T[]): T { return arr[0]; } first([1, 2, 3]); first(["a", "b"]); ``` ## Graph ```mermaid flowchart TD A[Generic Function] --> B[T = number] A --> C[T = string] ``` ## Remember - Generics = flexible + safe - Avoid any when generics fit

#TypeScript#Intermediate#Generics