Guided Notes
Generics
Writing reusable type-safe functions, interfaces and classes with type parameters, constraints with extends, defaults, and generic utility patterns.
Why generics
Slide 1 / 4Without generics you choose between: • function first(items: number[]): number — only works for numbers, or • function first(items: any[]): any — works for everything but loses the type.
Generics keep the type flowing through: function first<T>(items: T[]): T | undefined { return items[0]; }
first([3, 1, 2]) is number | undefined; first(["a"]) is string | undefined. T is a type parameter — a variable for a type.
