Sub topic 3
Adding and removing readonly and optional modifiers
This chapter assumes you can read basic mapped types such as { [K in keyof T]: T[K] }, and that you know generics, type aliases, and the difference between a required property and an optional one. Here you will learn the four modifier operators and how to use them to build tools like Mutable, Required, and a "make only these keys optional" helper.
Two modifiers, four operators
A property in an object type can carry two modifiers:
readonlyprevents assignment to the property after the object is created.?marks the property as optional, so it may be missing.
A mapped type can change both modifiers on every property it produces. Each modifier can be added or removed, which gives four operators.
| Written in the mapped type | Effect on each property |
|---|---|
| `readonly [K in keyof T]` or `+readonly [K in keyof T]` | Adds `readonly` |
| `-readonly [K in keyof T]` | Removes `readonly` |
| `[K in keyof T]?` or `[K in keyof T]+?` | Adds `?` |
| `[K in keyof T]-?` | Removes `?` |
The + prefix is the default, so +readonly and readonly mean the same thing. Writing + is only useful when you want to make the intent obvious next to a - on the other modifier.
Where the operator goes matters. readonly and -readonly go before the opening bracket. ? and -? go after the closing bracket, before the colon.
Adding modifiers
Adding ? to a mapped type rebuilds the built-in Partial.
type User = { id: number; name: string };
type MyPartial<T> = { [K in keyof T]?: T[K] };
type PartialUser = MyPartial<User>;
// { id?: number; name?: string }
const draft: PartialUser = {}; // allowed: every key is optional
const named: PartialUser = { name: "Ada" };Adding readonly rebuilds Readonly.
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type FrozenUser = MyReadonly<User>;
// { readonly id: number; readonly name: string }
const u: FrozenUser = { id: 1, name: "Ada" };
// u.name = "Grace"; // error: Cannot assign to 'name' because it is a read-only property.You can combine the operators in one mapped type. This type makes everything optional and readonly at once:
type ReadonlyPartial<T> = { readonly [K in keyof T]?: T[K] };Removing modifiers
The - prefix removes a modifier. -readonly produces a mutable copy of a type, and -? produces a type where every property is required.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Concrete<T> = { [K in keyof T]-?: T[K] };
type Config = { readonly host: string; port?: number };
type MutableConfig = Mutable<Config>;
// { host: string; port?: number }
type ConcreteConfig = Concrete<Config>;
// { readonly host: string; port: number }Each operator touches only its own modifier. Mutable leaves port optional, and Concrete leaves host readonly. To remove both, put both operators in one type:
type Plain<T> = { -readonly [K in keyof T]-?: T[K] };
type PlainConfig = Plain<Config>;
// { host: string; port: number }The built-in Required<T> is the same as Concrete. There is no built-in Mutable, which is why many codebases define their own.
What `-?` does to `undefined`
An optional property port?: number is read as number | undefined. When -? removes the optional marker, it also strips the undefined that the marker added. That is why ConcreteConfig["port"] is number, not number | undefined.
type PortType = Concrete<Config>["port"]; // numberThis behavior applies under strictNullChecks. If you turn on exactOptionalPropertyTypes, an undefined that you wrote yourself, as in port?: number | undefined, is kept, and only the implicit one is removed.
Modifiers are copied only by homomorphic mapped types
The examples above did not say what happens when you write no operator at all. In { [K in keyof T]: T[K] }, the mapped type iterates directly over keyof T, where T is a type parameter. TypeScript calls this a homomorphic mapped type, and it copies the readonly and ? modifiers from each original property.
type Copy<T> = { [K in keyof T]: T[K] };
type CopyConfig = Copy<Config>;
// { readonly host: string; port?: number }A mapped type over an unrelated key union has no source property to copy from, so the modifiers are lost.
type Loose<T> = { [K in "host" | "port"]: string };
// { host: string; port: string } with no modifiers at allThis matters for modifier work. -readonly and -? only have something to remove when the mapped type is homomorphic. The next chapter covers the rules for recognizing homomorphic mapped types in more detail.
Changing modifiers on only some keys
The operators apply to every property. To change a few keys, split the type into two parts, change one part, and put them back together with an intersection.
type Simplify<T> = { [K in keyof T]: T[K] };
type PartialBy<T, K extends keyof T> =
Simplify<Omit<T, K> & Partial<Pick<T, K>>>;
type RequireBy<T, K extends keyof T> =
Simplify<Omit<T, K> & Required<Pick<T, K>>>;
type ReadonlyBy<T, K extends keyof T> =
Simplify<Omit<T, K> & Readonly<Pick<T, K>>>;
type Account = { readonly id: number; name: string; email?: string };
type NewAccount = PartialBy<Account, "name">;
// { readonly id: number; name?: string; email?: string }
type ContactableAccount = RequireBy<Account, "email">;
// { readonly id: number; name: string; email: string }
type LockedAccount = ReadonlyBy<Account, "name">;
// { readonly id: number; readonly name: string; email?: string }Pick and Omit keep the modifiers of the keys they leave in, so id stays readonly in every result. Simplify is a homomorphic mapped type that does nothing except flatten the intersection into one object type. Without it, hovering over the result shows Omit<...> & Partial<...>, and some tools treat the intersection differently from a plain object type.
Gotchas
Modifiers are shallow
Mutable<T> and Readonly<T> change only the top-level properties. A nested object keeps its own modifiers.
type Settings = { readonly ui: { readonly theme: string } };
type S = Mutable<Settings>;
// { ui: { readonly theme: string } }To change nested levels you need a recursive mapped type, which a later chapter covers.
`readonly` does not affect assignability
TypeScript lets you assign a readonly object to a variable with a mutable type. The check only blocks writes through the readonly type.
type RO = { readonly n: number };
type RW = { n: number };
const a: RO = { n: 1 };
const b: RW = a; // allowed, no error
b.n = 2; // this also changes a.n at runtimeSo Readonly<T> is a guard against mistakes in code that sees that type. It does not make the value immutable, and it does not stop a mutable alias from changing the data. readonly exists only at compile time and produces no JavaScript.
Arrays and tuples
When a homomorphic mapped type is applied to an array or tuple type, TypeScript maps the elements and keeps the array shape. The modifiers then apply to the array as a whole or to each tuple slot.
type A = Mutable<readonly string[]>; // string[]
type B = Partial<[number, string]>; // [number?, string?]
type C = Readonly<string[]>; // readonly string[]This works only when the mapped type is generic in T and T is the array type, as in the helpers above. A hand-written mapped type over a concrete array type does not behave this way.
`Partial` is not the same as allowing `undefined`
Partial<{ a: number }> lets you omit a. It does not forbid or require anything about passing undefined explicitly. By default, { a: undefined } is allowed, because an optional property accepts undefined. Under exactOptionalPropertyTypes it is an error.
Summary of decisions
- To make every property optional or required, use
?or-?, or the built-insPartialandRequired. - To make every property readonly or mutable, use
readonlyor-readonly. Use the built-inReadonly, and defineMutableyourself. - To change a subset of keys, split with
PickandOmit, change one half, and flatten withSimplify. - To change nested properties, you need recursion. A single mapped type is not enough.
Exercise
Given type Job = { readonly id: string; title: string; due?: Date }, write a generic helper Unlock<T, K extends keyof T> that removes readonly from only the keys in K, and show the type of Unlock<Job, "id">.
Show answer
Split the type into the unlocked keys and the rest, strip readonly from the first part, and flatten:
type Simplify<T> = { [K in keyof T]: T[K] };
type Unlock<T, K extends keyof T> =
Simplify<Omit<T, K> & { -readonly [P in keyof Pick<T, K>]: T[P] }>;
type Result = Unlock<Job, "id">;
// { id: string; title: string; due?: Date }
An equally valid form is Omit<T, K> & Mutable<Pick<T, K>> inside Simplify, using the Mutable helper from this chapter. Omit keeps the modifiers of the remaining keys, and Pick keeps due optional where it applies.
Exercise
What is the type of Check["b"] in this code, and why?
type Check = Required<{ a: number; b?: string | undefined }>;
Show answer
Under strictNullChecks without exactOptionalPropertyTypes, Check["b"] is string. -? removes the optional marker and also strips the undefined that came with it, and without exactOptionalPropertyTypes it cannot tell that undefined apart from the one written in the declaration. With exactOptionalPropertyTypes on, the explicit | undefined is kept and the result is string | undefined.