Partial
Make every property of a type optional with Partial.
Syntax
Partial<User>Partial<T> is a built-in utility type that takes a type and makes all of its properties optional. It is perfect for update functions where the caller supplies only the fields they want to change.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A PATCH endpoint accepts Partial<User> so callers only need to send the fields they want to update.
- A test helper uses Partial<Config> to let tests override only the relevant configuration properties.
- A form state is typed as Partial<FormData> so fields start undefined and get filled in progressively.
More examples
Partial makes all props optional
Partial<User> makes every User field optional so a patch function only requires the fields being changed.
interface User {
id: number;
name: string;
email: string;
}
function updateUser(id: number, patch: Partial<User>): void {
// patch may contain any subset of User fields
console.log('Updating', id, 'with', patch);
}
updateUser(1, { name: 'Alice' }); // only name
updateUser(2, { email: '[email protected]' }); // only emailMerging with defaults
Combines a full defaults object with a Partial override to produce a complete Config without requiring all keys from the caller.
interface Config {
timeout: number;
retries: number;
verbose: boolean;
}
const defaults: Config = { timeout: 5000, retries: 3, verbose: false };
function createConfig(overrides: Partial<Config>): Config {
return { ...defaults, ...overrides };
}
const cfg = createConfig({ timeout: 10000 });Partial in a class
Uses Partial<User> in a store's update method to allow callers to specify only the fields they want to change.
class UserStore {
private data: Map<number, User> = new Map();
update(id: number, changes: Partial<User>): void {
const existing = this.data.get(id);
if (existing) {
this.data.set(id, { ...existing, ...changes });
}
}
}
interface User { id: number; name: string; email: string; }
Discussion