QTypeScript · Interview preparation
When is Partial useful in TypeScript?
Partial makes every property of a type optional.
The idea to remember.
Partial makes every property of a type optional. It can model a patch object, but a validated update API should still restrict which fields a caller may change.
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 when is Partial useful in TypeScript 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 ↗