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 / 4

Without 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.

← Classes & Access Modifiers