Utility Types - Partial
In this page:
Basic Partial
Partial<T> allows an object to contain any subset of T's original properties, turning every required property into an optional one without you having to rewrite the whole type by hand.
Example: Basic Partial
interface Todo {
title: string;
done: boolean;
}
type PartialTodo = Partial<Todo>;
const t: PartialTodo = { title: "Buy milk" };
console.log(t);
Partial for Updates
Partial is especially useful when a function updates only selected properties of an object, since the caller shouldn't be forced to pass every single field just to change one of them.
Example: Partial for Updates
interface Todo {
title: string;
done: boolean;
}
function updateTodo(todo: Todo, changes: Partial<Todo>): Todo {
return { ...todo, ...changes };
}
const updated = updateTodo({ title: "Buy milk", done: false }, { done: true });
console.log(updated);
Partial with Interfaces
Partial works with interfaces just as well as with type aliases, and it preserves each property's original type while only changing whether that property is required or optional.
Example: Partial with Interfaces
interface Settings {
theme: string;
fontSize: number;
}
const patch: Partial<Settings> = { fontSize: 14 };
console.log(patch);
Partial and Type Safety
Partial does not remove type checking on the properties that are supplied — any property that is present in the object must still match its original type exactly, only its presence becomes optional.
Example: Partial and Type Safety
interface Todo {
title: string;
done: boolean;
}
const patch: Partial<Todo> = { done: true };
console.log(typeof patch.done);
When to Use Partial
Use Partial when an operation can legitimately accept any subset of an existing object's properties, such as a generic patch or update function in an API client.
Example: When to Use Partial
interface User {
name: string;
email: string;
}
function patchUser(id: number, changes: Partial<User>) {
console.log("Patching user", id, changes);
}
patchUser(1, { email: "[email protected]" });
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates