Conditional Modifier Application
What you'll learn: How to use conditional types within mapped types to selectively apply modifiers like readonly or optional based on each property's type.
The Core Idea
So far, you've learned to apply modifiers uniformly across all properties in a mapped type—making everything optional, or everything readonly. But what if you only want to make certain properties optional based on their type? For example, making function properties optional but leaving primitives required.
Conditional modifier application combines mapped types with conditional types to make dynamic decisions about whether to apply ? or readonly to each property as you iterate over it.
The Pattern
Instead of blindly adding ? or readonly to every property, you use a conditional type to check the property's type first:
type ConditionalOptional<T> = {
[K in keyof T as T[K] extends Function ? K : never]?: T[K]
} & {
[K in keyof T as T[K] extends Function ? never : K]: T[K]
}
This creates two separate mapped types, then intersects them. One makes function properties optional; the other leaves non-functions required.
Simpler Approach with Conditional Modifiers
You can also apply the modifier conditionally inline:
type OptionalFunctions<T> = {
[K in keyof T]: T[K] extends Function
? T[K] | undefined
: T[K]
}
This checks each property: if it's a function, add | undefined; otherwise, leave it as-is.
When This Matters
Conditional modifier application shines when building APIs where certain types of properties should behave differently—like making all callback handlers optional, or making all primitive fields readonly while keeping objects mutable.
Key Takeaway:
Conditional types inside mapped types let you selectively apply modifiers based on property types, enabling fine-grained control over which properties become optional, readonly, or otherwise transformed.