Modifier Precedence and Ordering
What you'll learn: How multiple modifier changes (+readonly, -?, etc.) combine and the order in which TypeScript applies them when building mapped types.
Understanding Modifier Interaction
When you apply multiple modifiers to the same property in a mapped type, TypeScript processes them in a specific, predictable order. You can change both the readonly status and the optionality (?) of properties simultaneously, but understanding how these changes layer on top of each other is crucial.
The good news: TypeScript applies all modifiers in parallel rather than sequentially. This means there's no "first readonly, then optional" processing. Instead, each modifier operates independently on the source property's characteristics.
How Multiple Modifiers Work Together
When you write a mapped type like this:
type MyMappedType<T> = {
-readonly [K in keyof T]+?: T[K]
};
TypeScript applies both transformations:
-readonlyremoves any readonly modifier+?adds optional status
These happen simultaneously to each property. There's no intermediate state where one applies before the other.
Ordering in Your Code
While the effects are parallel, the syntax order matters for readability. The TypeScript convention is:
- Readonly modifier (
+readonlyor-readonly) comes first - Optional modifier (
+?or-?) comes second
This isn't enforced by the compiler—TypeScript accepts them in either order—but following this convention makes your code more predictable for other developers.
Why This Matters
When you stack modifiers, understanding their independence prevents confusion. Removing readonly doesn't affect whether a property becomes optional, and vice versa. Each modifier targets a different aspect of the property's type signature.
Key Takeaway: Multiple modifiers in mapped types apply independently and in parallel, though convention places readonly before optionality for consistency.