Skip to content
TypeScript·Intermediate·Coding·1 min read

What problem do generics solve?

Short interview answer

Generics express relationships between types while preserving information. An identity function using T returns the same type it receives; using unknown would lose that relationship and require narrowing or assertion at the call site.

Example

TypeScript
function first<T>(arr: T[]): T | undefined {  return arr[0];}
first([1, 2, 3]);        // number | undefinedfirst(['a', 'b']);       // string | undefined  — relationship preserved

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Generics

Related questions