Advertisement
Intermediate TypeScript, Mapped Types

How do the '+'/'-' modifiers work with '?' and 'readonly' in a mapped type?

Short answer

By default, a mapped type COPIES existing modifiers ('?' and readonly) from the source type; explicitly writing `-?` or `-readonly` REMOVES that modifier from every mapped property, while `+?` or `+readonly` (equivalent to just writing them plainly) explicitly ADDS it — this is…

Save TypeScript mock interview
Advertisement
AModel answer
By default, a mapped type COPIES existing modifiers ('?' and readonly) from the source type; explicitly writing `-?` or `-readonly` REMOVES that modifier from every mapped property, while `+?` or `+readonly` (equivalent to just writing them plainly) explicitly ADDS it — this is how built-in Required<T> and Writable-style utilities are implemented.
type Required<T> = { [K in keyof T]-?: T[K] }; // removes optionality
type Mutable<T> = { [K in keyof T]-readonly: T[K] }; // removes readonly

interface Config { readonly name?: string; }
type FullyMutableRequired = Mutable<Required<Config>>;
// { name: string }
Real-world example
Building custom utility types that strip readonly or optionality from a type, mirroring built-in Required<T>.
Likely follow-ups
  • What is the built-in Readonly<T> utility type's mapped-type implementation?
Related topics