QTypeScript · Interview preparation
How does infer work in conditional types?
infer names a type captured from a conditional type pattern.
The idea to remember.
infer names a type captured from a conditional type pattern. It is useful for extracting function results, parameter lists or nested generic values.
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 does infer work in conditional types 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 ↗