Sub topic 10
Changing modifiers in bulk: Partial, Required, Readonly, -? and -readonly
This chapter assumes you know how to declare an interface with an optional (?) or readonly property. It also assumes you know that an optional property has the type T | undefined when you read it. If those ideas are new, review the earlier chapters on optional and readonly properties first.
Marking properties one at a time works for small types. It becomes tedious when you need a variant of an existing type: a draft where every field is optional, a validated version where every field is present, or a frozen snapshot. TypeScript lets you derive these variants from one source type instead of writing and maintaining each by hand.
The built-in utility types
TypeScript ships three utility types that change modifiers on every property at once.
| Utility type | Effect on every property | Result |
|---|---|---|
| `Partial<T>` | Adds `?` | All properties optional |
| `Required<T>` | Removes `?` | All properties required |
| `Readonly<T>` | Adds `readonly` | All properties read-only |
Here is a source type and the three variants:
interface User {
id: number;
name: string;
email?: string;
}
type UserDraft = Partial<User>;
// { id?: number; name?: string; email?: string }
type CompleteUser = Required<User>;
// { id: number; name: string; email: string }
type FrozenUser = Readonly<User>;
// { readonly id: number; readonly name: string; readonly email?: string }
const draft: UserDraft = {}; // OK
const frozen: FrozenUser = { id: 1, name: "Ada" }; // OK
// frozen.name = "Grace"; // Error: Cannot assign to 'name' because it is a read-only property.Readonly<User> keeps email optional. Each utility changes one modifier and leaves the other alone.
A common use: update functions
Partial<T> fits functions that accept some of an object's fields and merge them into the whole.
interface User {
id: number;
name: string;
email?: string;
}
function update(user: User, changes: Partial<User>): User {
return { ...user, ...changes };
}
const ada: User = { id: 1, name: "Ada" };
const renamed = update(ada, { name: "Ada Lovelace" });
console.log(renamed); // { id: 1, name: 'Ada Lovelace' }Spreading changes after user means any key present in changes overwrites the original. That has a trap, covered later in this chapter: a key that is present with the value undefined also overwrites.
How they work: mapped types
The utilities are ordinary mapped types. A mapped type builds a new object type by looping over the keys of another type. You can write the three utilities yourself:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };Read [K in keyof T] as "for each key K of T". The text after the bracket describes each new property: its modifiers, then its type T[K].
Two operators control modifiers inside a mapped type:
?or+?adds optionality.readonlyor+readonlyadds read-only. The+is the default and is usually left out.-?removes optionality.-readonlyremoves read-only.
The minus forms have no shorthand spelled out in the language. They exist only inside mapped types, which is why Required<T> is defined with -?.
Mapped types over `keyof T` copy modifiers
A mapped type of the form { [K in keyof T]: ... } is called homomorphic. Because the keys come directly from keyof T, TypeScript copies each property's existing ? and readonly to the new property. That is why Partial<User> does not lose any readonly marks, and Readonly<User> keeps email optional. You only write a modifier when you want to change what the source had.
interface Profile {
readonly id: number;
nickname?: string;
}
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Filled<T> = { [K in keyof T]-?: T[K] };
type EditableProfile = Mutable<Profile>;
// { id: number; nickname?: string }
type FullProfile = Filled<Profile>;
// { readonly id: number; nickname: string }Mutable<T> is not in the standard library, but you will meet it often. It is the inverse of Readonly<T>, and you define it yourself.
You can use both minus operators in one mapped type:
type Plain<T> = { -readonly [K in keyof T]-?: T[K] };
type PlainProfile = Plain<Profile>;
// { id: number; nickname: string }What `-?` does to the type
Removing ? changes more than the marker. An optional property read from an object has the type string | undefined. When -? removes the optionality, TypeScript also removes the undefined that optionality added, so the property becomes plain string.
interface Contact {
phone?: string;
}
type RequiredContact = Required<Contact>;
function call(c: RequiredContact): number {
return c.phone.length; // OK: phone is string, not string | undefined
}This is why Required<T> is useful after validation. Once you have checked that every field is present, you can pass the result around as Required<T> and downstream code does not need to check for undefined again.
The compiler does not check that your validation really ran. If you cast an object to Required<Contact> without filling in phone, call will fail at runtime. The type records a promise. It does not enforce one.
Limits to know
All three are shallow
Partial, Required and Readonly change only the top-level properties. Nested objects keep their original modifiers.
interface Settings {
ui: { theme: string; fontSize: number };
}
type Draft = Partial<Settings>;
const d: Draft = {
ui: { theme: "dark" }, // Error: Property 'fontSize' is missing in type '{ theme: string; }'
};Partial<Settings> makes ui optional. It does not make theme or fontSize optional inside it. The same shallow rule applies to Readonly<T>: a nested ui.theme stays assignable. For deep versions you need a recursive mapped type, which a later chapter covers.
Partial and `undefined` values
Under the default compiler settings, an optional property accepts an explicit undefined. Combined with spreading, this can erase data:
interface User {
id: number;
name: string;
email?: string;
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]" };
const changes: Partial<User> = { email: undefined };
const result: User = { ...ada, ...changes };
console.log(result.email); // undefined — the existing email was overwrittenThe compiler accepts this because { email: undefined } is a valid Partial<User>. If you want "omit means keep, and undefined is not a valid value", turn on exactOptionalPropertyTypes. Then { email: undefined } is rejected for Partial<User>, because email?: string no longer allows an explicit undefined.
Arrays and tuples are handled specially
When a homomorphic mapped type is applied to an array or tuple type, TypeScript maps the elements and produces another array or tuple type.
type A = Readonly<string[]>; // readonly string[]
type B = Partial<[number, string]>; // [number?, string?]
type C = Readonly<[number, string]>; // readonly [number, string]So Readonly<string[]> gives you the same type as writing readonly string[].
Non-homomorphic mapped types lose modifiers
If the keys do not come from keyof T on the same type, TypeScript has nothing to copy from. Record<K, V> is an example: it builds a fresh object type, and every property is required and mutable.
type Flags = Record<"a" | "b", boolean>;
// { a: boolean; b: boolean }, with no optional or readonly marksPick<T, K> is treated as homomorphic, so it keeps the source property's modifiers. Omit<T, K> is built on Pick, so it keeps them too.
Changing only some properties
The built-in utilities act on every property. To change only a few, combine Omit, Pick and an intersection:
interface Article {
id: number;
title: string;
body: string;
}
type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type NewArticle = WithOptional<Article, "id" | "body">;
// { title: string } & { id?: number; body?: string }
const first: NewArticle = { title: "Hello" };
const second: NewArticle = { title: "Again", body: "Text" };NewArticle is a good fit for creating a record where the database assigns id afterward. The same pattern works with Readonly and Required. Swap Partial for the utility you need.
An intersection works for most uses. Hovering over it in an editor shows Omit<...> & Partial<...> rather than one flat object, which can make error messages harder to read. If that bothers you, wrap the result in a mapped type to flatten it:
type Flatten<T> = { [K in keyof T]: T[K] };
type NewArticleFlat = Flatten<WithOptional<Article, "id" | "body">>;
// { title: string; id?: number; body?: string }Choosing between a variant and a separate type
Deriving types keeps them in sync: add a field to User and UserDraft gets it too. Derivation also has costs.
- Use a derived variant when the new type really is "the same shape with different modifiers", such as drafts, patches and snapshots.
- Write a separate interface when the two shapes will diverge. A
UserDraftthat later needs fieldsUsernever had should stop beingPartial<User>. - Avoid chains of three or four stacked utilities. If a reader cannot guess the result, name an intermediate type or write the shape out.
Common mistakes
- Expecting deep behavior.
Readonly<Config>still lets you callconfig.tags.push("x")whentagsis a mutable array. - Using
Partialfor the return value of a function that always fills every field. The caller then has to handleundefinedfor no reason. - Treating
Required<T>as validation. It changes the type only. Nothing runs at runtime. - Forgetting
-readonlywhen you copy. A function that builds a modified copy of aReadonly<T>value needsMutable<T>as its working type, or it cannot set fields. - Spreading a
Partialover a full object without considering explicitundefinedvalues, as shown above.
Exercise
Given interface Job { readonly id: string; title: string; assignee?: string }, write a type OpenJob that has the same properties as Job but with id mutable and assignee required. Then say what the type of assignee is in OpenJob.
Show answer
Use a mapped type that applies both minus operators: type OpenJob = { -readonly [K in keyof Job]-?: Job[K] };. The result is { id: string; title: string; assignee: string }. The type of assignee is string, not string | undefined, because -? removes the undefined that optionality added. Equivalent: type OpenJob = Required<{ -readonly [K in keyof Job]: Job[K] }>.
Exercise
Why does Readonly<{ tags: string[] }> not stop obj.tags.push("x"), and which tool from this chapter's limits section would you need to prevent it?
Show answer
Readonly<T> is a shallow mapped type. It marks the tags property itself as read-only, so obj.tags = [] is an error, but the array stored in tags keeps its own mutable type, so push is allowed. To block push you need either a readonly string[] property type or a recursive deep-readonly mapped type that applies readonly at every level.