Generics allow TypeScript code to work with multiple types while preserving type safety. A type parameter <T> acts as a placeholder filled at call site or inferred by the compiler. Constraints (T extends ...) restrict what types a generic accepts. The infer keyword extracts types from complex type expressions inside conditional types. Generic inference eliminates the need to manually specify type arguments in most cases.
Using infer to extract types from complex type expressions.
An unconstrained <T> can only call methods that exist on all types (essentially nothing useful). T extends { id: number } lets you access .id. Constraints make generics practical.
TypeScript infers generic parameters from call-site arguments in almost all cases. Writing identity<string>("hello") instead of identity("hello") is noise. Inference is the default — use explicit only when needed.
The built-in ReturnType, Parameters, InstanceType, and Awaited utilities all use infer. Understanding infer unlocks the ability to write any type-level transformation.
Sign in to share your feedback and join the discussion.