Advanced Generics: Overloads, Inference Tricks, and Variance
Interview-focused advanced generics: overloads, inference patterns, variance basics, and designing ergonomic typed APIs.
Frontend Interview Team
February 08, 2026
30‑second interview answer
Advanced generics are about designing APIs that are safe and ergonomic. You often combine generics with overloads for better call signatures, use inference (infer) to keep usage simple, and understand variance enough to avoid unsafe function typing. In interviews, focus on practical patterns (typed helpers, API clients, hooks).
Overloads (common interview topic)
Overloads let you provide multiple call signatures:
function pick(obj: { a: string }, key: 'a'): string;
function pick(obj: any, key: string) {
return obj[key];
}
pick({ a: 'x' }, 'a'); // stringWhen overloads help
- functions with different input shapes
- APIs that return different types based on args
Designing for inference
Bad API (forces manual generics):
function wrap<T>(value: T): { value: T } { return { value }; }This is actually fine because inference works.
But inference fails when generics are not connected to parameters.
Rule:
“Make sure T appears in a function parameter so TS can infer it.”
Variance (keep it interview-safe)
Variance describes how types behave when substituted.
In practice:
- function parameter types are contravariant-ish
- return types are covariant
Interview-safe line:
“I avoid forcing complex variance rules; I rely on compiler errors and keep APIs simple.”
Practical patterns
Typed event emitter
type EventMap = { ready: void; error: Error };
function on<K extends keyof EventMap>(event: K, cb: (payload: EventMap[K]) => void) {
// ...
}
on('error', (e) => e.message);Generic function with constraint
function getProp<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}Mini Q&A
Q1: When do you use overloads?
- when the return type depends on input shape.
Q2: How do you make inference work?
- connect generics to function parameters.
Q3: What’s variance in one line?
- how subtyping works through generics and function types.
Summary checklist
- I can explain overloads with an example.
- I know how to design for inference.
- I can write safe
K extends keyof Thelpers.