Question presented to candidate:
"What are generics in TypeScript? Show me a function where a generic is better than any, and tell me where you see generics in everyday code."
What a strong answer should cover:
- A generic is a type parameter (
<T>): a placeholder filled in per call or per use, so one piece of code works for many types without losing type information - Why not
any:anyswitches checking off for the result, whileTlinks the input type to the output type (first<T>(items: T[]): T | undefined) - Type arguments are usually inferred from the call, and can be passed explicitly (
first<string>([])); aconstresult keeps a literal type - Generics appear on functions, type aliases, interfaces and classes:
Array<T>,Promise<T>,Map<K, V>,Result<T, E>, aStack<T> - Generics are erased: they do not exist at run time, so you cannot
new T()or checktypeof T - Rule of thumb: a type parameter should appear at least twice (relate two things); otherwise a plain type is simpler
Code / implementation expected: Yes β a small generic function (identity, first, pair) and ideally a generic interface or class.