Sub topic 4
Optional and readonly properties
This chapter assumes you know interface and type alias syntax, and that you have read the earlier chapters on assignability as a relation between a source type and a target type, and on structural typing. Here you will see how the ? and readonly modifiers on a property change that relation. The two modifiers behave very differently. Optionality affects whether an assignment compiles. readonly mostly does not.
Optional properties in the target
A property marked ? may be missing from a value. When the target declares a property as optional, a source does not need to have it.
interface Target {
id: number;
nickname?: string;
}
const noNick = { id: 1 };
const withNick = { id: 1, nickname: "Ann" };
const t1: Target = noNick; // OK: nickname is optional, so absence is fine
const t2: Target = withNick; // OK: present and stringIf the source does have the property, its type must still be assignable to the target's property type. Under strictNullChecks, reading an optional property gives string | undefined, because the property may be absent.
Optional in the source, required in the target
The reverse direction fails. A source that might lack a property cannot stand in for a target that demands it.
interface Source {
id: number;
nickname?: string;
}
interface Strict {
id: number;
nickname: string;
}
declare const s: Source;
const strict: Strict = s;
// Error: Property 'nickname' is optional in type 'Source' but required in type 'Strict'.Think of it in terms of sets. Every value of Strict has a nickname. Some values of Source do not. So Source contains values that are outside Strict, and the assignment is rejected.
Optional is not the same as `| undefined`
A required property whose type includes undefined must still be present. Only ? allows the key to be missing.
interface RequiredUndefined {
n: number | undefined;
}
interface OptionalNumber {
n?: number;
}
const a: RequiredUndefined = {}; // Error: Property 'n' is missing
const b: OptionalNumber = {}; // OK
const c: RequiredUndefined = { n: undefined }; // OKGoing the other way, an object with an optional n is not assignable to a target with a required n: number | undefined. The source may omit the key, so the "optional but required" error applies again.
exactOptionalPropertyTypes
By default, n?: number means the property may be absent or may hold undefined. Writing { n: undefined } is accepted. The compiler option exactOptionalPropertyTypes (not part of strict) separates the two cases. With it enabled, n?: number allows absence but not an explicit undefined.
interface Settings {
width?: number;
}
interface SettingsLoose {
width?: number | undefined;
}
// With "exactOptionalPropertyTypes": true
const ok: Settings = {};
const bad: Settings = { width: undefined };
// Error: Type 'undefined' is not assignable to type 'number'
// with 'exactOptionalPropertyTypes: true'.
declare const strictSettings: Settings;
const loose: SettingsLoose = strictSettings; // OK: narrower value set
declare const looseSettings: SettingsLoose;
const tight: Settings = looseSettings; // Error under the optionThe option matters when code distinguishes "key missing" from "key set to undefined", for example with "width" in obj or Object.keys. If you write { ...defaults, ...overrides } and overrides.width is undefined, the spread overwrites the default with undefined. The option helps catch that.
readonly does not affect assignability
readonly stops you from assigning to a property through a particular reference. It does not make the type incompatible with a mutable one. A source with readonly properties is assignable to a target without them, and the reverse is also allowed.
interface ReadonlyPoint {
readonly x: number;
readonly y: number;
}
interface MutablePoint {
x: number;
y: number;
}
const fixed: ReadonlyPoint = { x: 1, y: 2 };
const loose: MutablePoint = fixed; // OK: readonly is ignored here
loose.x = 10;
console.log(fixed.x); // 10
// fixed.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.This is deliberate. The compiler treats readonly as a restriction on one access path. It does not track that another alias exists. Rejecting this assignment would break a lot of existing code, such as passing a readonly object to an older function that never mutates it but whose parameter type omits the modifier.
readonly is shallow
readonly applies to the property itself, not to the value it holds. A readonly property holding an array still lets you modify the array's contents.
interface Config {
readonly tags: string[];
}
const cfg: Config = { tags: ["a"] };
cfg.tags.push("b"); // OK: the array is mutable
// cfg.tags = []; // Error: Cannot assign to 'tags' because it is a read-only property.For a deeply read-only structure, you need to mark each level, or use readonly string[] for the array.
The exception: readonly arrays and tuples
Arrays and tuples are the place where readonly does affect assignability. readonly number[] has no push or pop, so it has fewer members than number[]. A mutable array is assignable to a readonly one, but not the other way.
const ro: readonly number[] = [1, 2];
const rw: number[] = ro;
// Error: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
const mutable: number[] = [1, 2, 3];
const view: readonly number[] = mutable; // OKThe next chapters on arrays and tuples cover this in more detail. For now, note the asymmetry with object properties: a readonly property modifier is ignored, while a readonly array type is a different type.
Summary of the rules
| Source property | Target property | Assignable? |
|---|---|---|
| missing | optional `x?: T` | Yes |
| missing | required `x: T` | No |
| optional `x?: T` | required `x: T` | No |
| required `x: T` | optional `x?: T` | Yes, if `T` fits |
| `readonly x: T` | mutable `x: T` | Yes |
| mutable `x: T` | `readonly x: T` | Yes |
| `x: T` | `x?: T` under `exactOptionalPropertyTypes` | Yes, if `T` has no `undefined` |
| `x: undefined` | `x?: T` under `exactOptionalPropertyTypes` | No |
Notice that the diagram never asks about readonly. For object properties, that check does not exist.
Common mistakes
- Treating
x?: Tandx: T | undefinedas interchangeable. Only the first lets callers omit the key. - Assuming
readonlymakes a value safe to share. It does not stop mutation through other references. - Passing an object with an optional property to a function that requires it, then "fixing" the error with
!oras. Narrow the value or supply a default instead. - Enabling
exactOptionalPropertyTypeslate in a project and being surprised by errors whereundefinedwas passed explicitly.
Exercise
Given interface A { a?: number } and interface B { a: number }, which of const x: A = bValue and const y: B = aValue compiles, where bValue: B and aValue: A? Explain why, using the source and target.
Show answer
Only const x: A = bValue compiles. A B always has a, so it satisfies the optional target A. An A may lack a, so as a source it cannot satisfy the required property in the target B, and the compiler reports that a is optional in type 'A' but required in type 'B'.
Exercise
After running the code below, what is logged, and why does the assignment on the third line compile? const p: { readonly n: number } = { n: 1 }; const q: { n: number } = p; q.n = 2; console.log(p.n);
Show answer
It logs 2. Assignability ignores readonly on object properties, so a source with a readonly property is assignable to a mutable target. q and p refer to the same object, so writing through q changes what p.n reads.