Generics parameterize types: function first<T>(items: T[]): T | undefined. Call sites infer T or pass it explicitly.
Why generics matter
They let you write reusable utilities without sacrificing type safety—no need to cast to any when the same function handles strings, numbers, or custom objects.
Self-check
- Write
function wrap<T>(value: T): { value: T }and call it with a string and a number.
Challenge
Identity generic
- Write
function identity<T>(value: T): T. - Call it with a string and a number; print both results.
Done when: both values print unchanged.
Interview prep
- Why use generics?
To reuse logic while preserving relationships between types (e.g. input array element type matches return type).