Generics and type-level tools · core
Generics and constraints
A generic is a type parameter that keeps the relationship between inputs and outputs (e.g. first<T>(xs: T[]): T | undefined), and extends constrains what can be passed in.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
function identity<T>(x: T): Tkeeps the exact type;(x: any) => anyloses it.- Constraints:
<T extends { id: string }>lets you read.idand still return the full T. <K extends keyof T>ties a key to an object:get<T, K extends keyof T>(obj: T, key: K): T[K].- Usually let TypeScript infer type arguments; pass them explicitly only when inference can't (e.g.
useState<User | null>(null)). - Defaults:
<T = unknown>.consttype parameters (TS 5.0) infer literal types:<const T>.
The red pen
Common traps: mistake → fix
Mistake: "generics are only for collections"
Fix: they are for any function or component whose output type depends on its input type.
Mistake: "T extends X means T is exactly X"
Fix: it means T is assignable to X and may have more properties.
Easy to hard
Questions interviewers ask, easy to hard
- What problem do generics solve? Show one you wrote.
- How do constraints work, with keyof?
- When must you pass a type argument explicitly?
- Write a typed groupBy.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.