Practical Partial: Update Functions
What you'll learn: How to use Partial<T> to create flexible update functions that accept a subset of an object's properties without duplicating type definitions.
The Update Function Problem
Imagine you have a User interface with many properties. You want to write an updateUser function that accepts only the fields the caller wants to change—not all of them. You could manually create a new interface with all properties marked optional, but that's duplicating work and breaks if User ever changes.
This is where Partial<T> shines.
The Pattern
interface User {
id: number;
name: string;
email: string;
age: number;
}
function updateUser(id: number, updates: Partial<User>): User {
// In real code, you'd fetch the user and merge updates
const existingUser: User = { id: 1, name: "Alice", email: "alice@example.com", age: 30 };
return { ...existingUser, ...updates };
}
// Works with any subset of properties
updateUser(1, { name: "Alicia" });
updateUser(1, { email: "new@example.com", age: 31 });
updateUser(1, {}); // Valid: update nothing
Why This Works
Partial<User> transforms every property of User to optional, so updates can contain zero, one, or all properties. TypeScript still enforces that if a property is present, it must have the correct type—you can't pass { age: "thirty" }.
You never wrote a separate UpdateUserInput interface, and if User gains a new property, your update function automatically supports updating it too.
Key Takeaway: Use Partial<T> to type update functions that accept flexible property subsets, keeping your codebase DRY and maintenance-friendly.