Generics
A generic parameterises a function, class, or type over a type variable, so the same code works for many types while preserving the exact type. The classic example is identity<T>(x: T): T: it returns precisely the type it received, so identity(5) is typed number, not a vague any.
That is exactly how a generic differs from any: any erases the type and switches off checking, while a type parameter keeps the link between input and output, staying fully type-safe. The idea then scales: constraints via extends and keyof narrow what callers may pass without losing precision, and the built-in utility types (Partial, Pick, Omit, Record) are generics over mapped types — reusable shape transforms. The full map lives in the layers below.
Topic map
- Generics — the type parameter
<T>, generic functions, classes, and interfaces; inference and why a generic is notany. - Generic Constraints —
<T extends U>as an upper bound,keyof, and<K extends keyof T>for safe indexing. - Utility Types —
Partial,Required,Pick,Omit,Record,Readonlyas generics over mapped types.
Common traps
| Mistake | Consequence |
|---|---|
Reaching for any instead of a type parameter | The input-to-output type link is lost — the compiler checks nothing further |
| Thinking generics exist at runtime | Like all types they are erased at compile time — there is no reflection over T |
Constraining a parameter with implements | A constraint is written with extends; implements is about classes, not type parameters |
Assuming <T extends U> pins T to U | extends sets an upper bound, not an exact type — T may be any subtype of U |
Confusing Pick and Omit | Pick<T, K> keeps keys K; Omit<T, K> drops them |
| Expecting utility types to run at runtime | They are compile-time type operations, not functions — you cannot call them |
Interview relevance
Generics are one of the most common TypeScript interview topics, because they sit on top of an understanding of the whole type system. A candidate who explains that a generic preserves the type where any loses it immediately shows maturity.
Typical checks:
- How a generic differs from
anyand whyidentity(5)isnumber, notany. - Whether the compiler can infer the type argument or you must pass it explicitly.
- How to constrain a parameter with
extendsand what<K extends keyof T>buys you. - How
Partial,Pick,Omit,Recordwork and that they compile to nothing. - The difference between
Pick/Omitand whatExcludeoperates on (a union, not object keys).
Common wrong answer: "a generic is just a prettier any". That opens the discussion that any breaks the input-to-output link while a generic keeps it, so one type-safe piece of code replaces a stack of overloads.