Sub topic 5
Required and Readonly
This chapter assumes you know TypeScript interfaces and type aliases, optional properties (name?: string), and generic syntax such as Array<T>. You will learn what Required<T> and Readonly<T> do, where each one helps, and where each one stops protecting you.
What the two types do
Partial<T> adds the ? modifier to every property. Required<T> and Readonly<T> handle the other two property modifiers.
Required<T>removes?from every property, so each property must be present.Readonly<T>addsreadonlyto every property, so the compiler rejects reassignment.
Both return a new type and leave the original unchanged.
interface 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 }Each utility changes one modifier and leaves the rest alone. Readonly<User> keeps email optional, and Required<User> does not make anything readonly.
Required: guaranteeing that values exist
Optional properties suit input that callers may leave out. Once you have filled in the gaps, the rest of your code should not keep checking for undefined. Required<T> describes that "all filled in" state.
interface Options {
host?: string;
port?: number;
secure?: boolean;
}
type ResolvedOptions = Required<Options>;
const defaults: ResolvedOptions = {
host: "localhost",
port: 8080,
secure: false,
};
function resolve(options: Options = {}): ResolvedOptions {
return {
host: options.host ?? defaults.host,
port: options.port ?? defaults.port,
secure: options.secure ?? defaults.secure,
};
}
const final = resolve({ port: 3000 });
console.log(final.host.toUpperCase()); // no undefined check neededThe public function accepts Options. Internal code receives ResolvedOptions, so it never has to ask whether host exists. You write the optional shape once and derive the strict shape from it. If you add a property to Options, defaults fails to compile until you give that property a default.
Required also removes undefined
The -? modifier that Required uses also strips undefined from the property type. In strict mode, email?: string is read as string | undefined. After Required, the property type is plain string.
interface Profile {
nickname?: string;
}
type StrictProfile = Required<Profile>;
// { nickname: string }
// const p: StrictProfile = { nickname: undefined };
// Error: Type 'undefined' is not assignable to type 'string'.A gotcha with spread
You may be tempted to write resolve with object spread instead:
interface Options {
host?: string;
port?: number;
}
const defaults: Required<Options> = { host: "localhost", port: 8080 };
function resolveWithSpread(options: Options): Required<Options> {
return { ...defaults, ...options };
}
const result = resolveWithSpread({ port: undefined });
console.log(result.port); // undefined, although the type says numberThis compiles, but the result is wrong. The type Options allows port to be present with the value undefined, and spread copies that undefined over the default. The ?? version above avoids the problem, because it falls back to the default for both a missing property and an explicit undefined.
Making only some properties required
Required<T> affects every property. To require only a few, combine it with Pick and an intersection:
interface Draft {
title?: string;
body?: string;
author?: string;
}
type Publishable = Draft & Required<Pick<Draft, "title" | "body">>;
const post: Publishable = { title: "Hello", body: "World" };
// const bad: Publishable = { title: "Hello" }; // Error: property 'body' is missingauthor stays optional, while title and body become mandatory. The chapter on composing utility types covers this pattern in more detail.
Readonly: blocking reassignment
Readonly<T> is useful when an object should not change after creation, such as configuration, function arguments, or state that you replace instead of editing.
interface Point {
x: number;
y: number;
}
const origin: Readonly<Point> = { x: 0, y: 0 };
// origin.x = 5;
// Error: Cannot assign to 'x' because it is a read-only property.
function move(p: Readonly<Point>, dx: number): Point {
return { x: p.x + dx, y: p.y }; // builds a new object instead of editing p
}
console.log(move(origin, 3)); // { x: 3, y: 0 }Marking a parameter Readonly<T> tells the caller that the function will not modify the argument. The compiler also stops the function body from modifying it by accident.
Readonly arrays
On an array type, Readonly produces a read-only array. It removes the methods that mutate the array, such as push, pop and sort:
function sum(values: readonly number[]): number {
return values.reduce((total, n) => total + n, 0);
}
const nums: Readonly<number[]> = [1, 2, 3];
// nums.push(4);
// Error: Property 'push' does not exist on type 'readonly number[]'.
console.log(sum(nums)); // 6
console.log(sum([4, 5])); // 9, a normal array is accepted tooA plain number[] can be passed where readonly number[] is expected. The reverse is an error, because a function that expects a mutable array could modify your read-only one.
Readonly is shallow
Readonly<T> marks only the top-level properties. Objects and arrays stored inside them stay mutable.
interface Config {
name: string;
tags: string[];
db: { host: string };
}
const config: Readonly<Config> = {
name: "app",
tags: ["a"],
db: { host: "localhost" },
};
// config.name = "other"; // Error: read-only
config.db.host = "remote"; // allowed
config.tags.push("b"); // allowed
console.log(config.db.host, config.tags); // remote [ 'a', 'b' ]For nested data you can write a recursive version. It is a custom utility type, and the mapped-type chapters explain how it works:
type DeepReadonly<T> = T extends (...args: never[]) => unknown
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
const strict: DeepReadonly<{ db: { host: string }; tags: string[] }> = {
db: { host: "localhost" },
tags: ["a"],
};
// strict.db.host = "remote"; // Error: read-only
// strict.tags.push("b"); // Error: 'push' does not exist on a readonly arrayThe first branch leaves functions unchanged, so the mapped type does not try to rebuild them.
Readonly is compile-time only
TypeScript erases types when it produces JavaScript. A readonly property is not protected at runtime, and code that bypasses the type system can still change it. To protect an object at runtime as well, use Object.freeze, which TypeScript types as returning a read-only version:
interface Point {
x: number;
y: number;
}
const frozen = Object.freeze({ x: 1, y: 2 });
// frozen has type Readonly<{ x: number; y: number }>
const asPoint = frozen as Point;
asPoint.x = 10; // compiles because of the cast, but fails at runtime in strict modeObject.freeze is also shallow, so nested objects stay mutable unless you freeze them too.
Readonly does not affect assignability
This is the least intuitive part of readonly. The compiler treats { readonly x: number } and { x: number } as compatible in both directions:
interface Point {
x: number;
y: number;
}
const frozen: Readonly<Point> = { x: 1, y: 2 };
const loose: Point = frozen; // allowed
loose.x = 99;
console.log(frozen.x); // 99The compiler allows this assignment, so Readonly<T> cannot stop a reference to the same object from being used to modify it. The protection applies only to accesses made through the read-only type.
Removing modifiers
Both utilities are built from mapped types, and a mapped type can also remove a modifier. A - before ? or readonly removes it. A + adds it, and is the default when you write the modifier alone.
| Modifier in a mapped type | Effect | Built-in that uses it |
|---|---|---|
| `?` | Makes the property optional | `Partial<T>` |
| `-?` | Makes the property required | `Required<T>` |
| `readonly` | Makes the property read-only | `Readonly<T>` |
| `-readonly` | Makes the property writable | None |
TypeScript has no built-in "opposite of Readonly", but one line gives you that:
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
interface Locked {
readonly id: number;
readonly label: string;
}
const draft: Mutable<Locked> = { id: 1, label: "a" };
draft.label = "b"; // allowed
console.log(draft); // { id: 1, label: 'b' }This is useful inside a function that builds an object step by step, then returns it as Readonly<T>.
Combining them
Utility types stack, and Required and Readonly change independent modifiers, so the order does not matter:
interface Settings {
theme?: "light" | "dark";
fontSize?: number;
}
type FinalSettings = Readonly<Required<Settings>>;
// { readonly theme: "light" | "dark"; readonly fontSize: number }
const settings: FinalSettings = { theme: "dark", fontSize: 14 };
// settings.theme = "light"; // Error: read-onlyThis combination fits a "resolved, immutable configuration" object. You declare it once, fill in all defaults, and treat it as fixed for the life of the program.
Common mistakes
- Expecting runtime protection. Neither
RequirednorReadonlyemits any JavaScript. They check types only. - Expecting depth. Both utilities affect only the top-level properties. Nested objects need a recursive utility such as
DeepReadonly. - Using
Requiredto supply values.Required<Options>says that values exist. It does not put them there. - Casting to silence errors. Writing
obj as Mutable<typeof obj>hides a deliberate design decision. If the code needs to mutate the object, change the type at its source instead.
Exercise
A function takes options: Options where every property of Options is optional. Inside, you build const merged: Required<Options> = { ...defaults, ...options }. It compiles, but merged.port is sometimes undefined at runtime. What causes this, and how do you fix it?
Show answer
The caller can pass { port: undefined }, which the Options type allows. Spread copies that undefined over the default, and the compiler does not flag it. Fix it by choosing each value explicitly, for example port: options.port ?? defaults.port, which falls back to the default for both a missing property and an explicit undefined.
Exercise
Given interface Config { name: string; tags: string[] } and const c: Readonly<Config> = { name: "a", tags: [] }, which of these lines is a compile error: c.name = "b", c.tags.push("x"), c.tags = ["y"]? Explain why.
Show answer
c.name = "b" and c.tags = ["y"] are errors, because Readonly makes the top-level properties name and tags read-only. c.tags.push("x") compiles, because Readonly is shallow: the array stored in tags is still a normal mutable string[]. To forbid the push, declare tags as readonly string[] or use a DeepReadonly type.