TypeScript Partial<T> Utility Type Explained
Learn how Partial<T> makes all properties of a type optional. Understand syntax, use cases, and practical examples for partial updates and configuration objects.
Detailed Explanation
Understanding Partial
Partial<T> is one of the most commonly used utility types in TypeScript. It constructs a type with all properties of T set to optional, effectively creating a type that represents any subset of T.
Syntax
type Partial<T> = {
[P in keyof T]?: T[P];
};
Basic Example
interface User {
id: number;
name: string;
email: string;
age: number;
}
type PartialUser = Partial<User>;
// Equivalent to:
// {
// id?: number;
// name?: string;
// email?: string;
// age?: number;
// }
Practical Pattern: Update Functions
The most common use of Partial<T> is in update or patch functions where you want to update only some fields of an object:
function updateUser(id: number, updates: Partial<User>): User {
const existing = getUserById(id);
return { ...existing, ...updates };
}
// Only update name and email -- other fields remain unchanged
updateUser(1, { name: "Alice", email: "alice@new.com" });
Deep Partial
Note that Partial<T> is shallow -- it only makes top-level properties optional. For deeply nested objects, you need a custom DeepPartial type:
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
Use Case
Use Partial<T> when building update/patch endpoints, configuration merging, or any function that accepts a subset of an object's properties. It is essential for CRUD operations where you want to update specific fields without requiring all of them.