Generics
Writing reusable, type-safe functions with generic type parameters, constraints, and overloads.
Why generics
Without generics, you'd either lose type safety (any) or duplicate a function for every type. A generic type parameter lets a function stay reusable while TypeScript still tracks the actual type through it:
Multiple type parameters
Generic constraints (extends)
Restricts a generic to types that have certain properties, so you can safely access them inside the function:
Default type parameters
keyof with generics
A very common pattern for writing a type-safe "get a property off an object" function:
Function overloads
Lets a function have multiple valid call signatures with different parameter/return types useful when the return type actually depends on the input in a way generics can't cleanly express:
Only the overload signatures are visible to callers the final "implementation" signature (with the optional params) is not itself a valid call shape.