QTypeScript · Interview preparation
How do generic constraints work?
An extends constraint tells TypeScript which capabilities a generic argument must provide.
The idea to remember.
An extends constraint tells TypeScript which capabilities a generic argument must provide. It lets code safely access required properties while retaining the caller's additional fields.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: a generic function
01 / BEGINNERKeep the relationship between the input and output type.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(['Ada', 'Lin']); // string | undefinedIntermediate: constrain a generic
02 / INTERMEDIATERequire a stable ID while preserving other fields.
function byId<T extends { id: string }>(items: T[]): Map<string, T> {
return new Map(items.map(item => [item.id, item]));
}Real scenario: typed API response
03 / REAL SCENARIOValidate runtime data; a generic type alone cannot validate JSON.
async function fetchJson<T>(url: string, guard: (x: unknown) => x is T): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error('Request failed');
const value: unknown = await response.json();
if (!guard(value)) throw new Error('Unexpected API payload');
return value;
}02Check your understanding
Try it in your own words.
Explain how do generic constraints work without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse TypeScript study guides ↗