TypeScript Generics Deep Dive: Constraints, Inference, and Real-World Patterns
TypeScript Generics Deep Dive: Constraints, Inference, and Real-World Patterns Generics are the most powerful feature in TypeScript that most developers underuse. Here's everything you need to go f...

Source: DEV Community
TypeScript Generics Deep Dive: Constraints, Inference, and Real-World Patterns Generics are the most powerful feature in TypeScript that most developers underuse. Here's everything you need to go from basic <T> to production-grade patterns. Why Generics Exist Without generics, you have two bad options: // Option 1: specific types (not reusable) function firstNumber(arr: number[]): number { return arr[0] } function firstString(arr: string[]): string { return arr[0] } // Option 2: any (loses type safety) function first(arr: any[]): any { return arr[0] } Generics give you option 3 — reusable AND type-safe: function first<T>(arr: T[]): T { return arr[0] } const num = first([1, 2, 3]) // type: number const str = first(['a', 'b', 'c']) // type: string Constraints with extends Constrain what types T can be: // T must have a .length property function getLength<T extends { length: number }>(value: T): number { return value.length } getLength('hello') // works: string has .leng