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
function first<T>(arr: T[]): T | undefined { return arr[0];}
first([1, 2, 3]); // number | undefinedfirst(['a', 'b']); // string | undefined — relationship preservedKey takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.