Combining Modifiers
What you'll learn: How to use readonly and ? (optional) together in a single mapped type to create powerful type transformations.
The Core Idea
In the previous lessons, you learned to apply modifiers separately—making properties optional with ? or immutable with readonly. But TypeScript lets you combine both modifiers in the same mapped type, giving you fine-grained control over object shapes.
Think of it like ordering coffee: you can have it iced, decaf, or both. Modifiers work the same way—you can mix and match them to create exactly the type you need.
Basic Syntax
type PartialReadonly<T> = {
readonly [K in keyof T]?: T[K];
};
This creates a type where every property is both optional and readonly. The order matters for readability, but both orderings work: readonly [K]? or ?readonly [K].
Practical Example
type User = {
id: number;
name: string;
email: string;
};
type UserSnapshot = {
readonly [K in keyof User]?: User[K];
};
const snapshot: UserSnapshot = {
id: 1
// name and email are optional
};
// snapshot.id = 2; // Error: Cannot assign to 'id' because it is read-only
Removing Multiple Modifiers
You can also use - to remove both:
type Mutable<T> = {
-readonly [K in keyof T]-?: T[K];
};
This strips both readonly and optional, forcing all properties to be required and writable.
Key Takeaway: Combining modifiers like readonly and ? in mapped types lets you apply multiple transformations at once, creating flexible utility types that match real-world constraints.