Creating Mutable Copies for Mutation Helpers
What you'll learn: How to temporarily strip readonly modifiers using mapped types so you can safely implement utility functions that update immutable data structures.
Why This Matters
Sometimes you need to write helper functions that update objects marked as readonly. While the final result should remain immutable, your internal implementation might need to mutate properties for efficiency or simplicity. You can use mapped types to create a temporary mutable copy, perform your updates, and return it as readonly.
The Core Pattern
When implementing update or patch utilities, you can remove readonly modifiers with the - operator:
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
This creates a version of type T where all properties can be written to, even if the original type had readonly properties.
Practical Example: An Update Helper
type User = {
readonly id: number;
readonly name: string;
readonly email: string;
};
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
function updateUser(user: User, changes: Partial<User>): User {
// Create mutable copy internally
const mutableCopy: Mutable<User> = { ...user };
// Now we can mutate properties
if (changes.name !== undefined) {
mutableCopy.name = changes.name;
}
if (changes.email !== undefined) {
mutableCopy.email = changes.email;
}
// Return as readonly User
return mutableCopy;
}
The function accepts a readonly object but works with a mutable copy internally, then returns the result as readonly again—maintaining the contract while simplifying the implementation.
Key Takeaway: Use -readonly in mapped types to create temporary mutable copies when implementing utility functions that update immutable data, giving you implementation flexibility while preserving type safety at the boundaries.