TypeScript · Types that pay for themselves
What are generics and why are they useful?
Short answer
Generics let a type or function work with many types while preserving the relationship between inputs and outputs. The compiler infers the type argument from usage, so callers keep precise types.
A generic is a type parameter, a placeholder that is filled in when the function or type is used. Unlike any, it keeps the connection between the argument and the result. If you pass an array of numbers, the return value is a number, not an unknown.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = first([1, 2, 3]);
const firstLabel = first(["alpha", "beta"]);What generics preserve
- The element type of an array or the value type of a map
- The relationship between a key and its property type
- The input and output of a function or promise
- Reusable data structures without losing type information
Generics are not a goal on their own. A function that only ever accepts one type does not need a type parameter. Add one when the caller's type should flow through the implementation, or when a type-level helper needs to be reusable across shapes.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How is a generic different from any?
- 2When does TypeScript infer a type argument?
- 3Can a generic have a default?
- 4When is a generic unnecessary?
Say it in the interview
Generics let me write a function or type that works across many types while keeping the relationship between input and output. For example, first returns the element type of whatever array it receives. The caller usually does not specify the type argument because it is inferred. I introduce generics when there is a real relationship to preserve, not just to make a function look flexible.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.