Sub topic 5
Optional and readonly properties
This chapter covers how the ? and readonly modifiers change what TypeScript accepts as assignable. It assumes you know interface and type alias syntax, basic object and array usage in JavaScript, and that strict mode is on in tsconfig.json. Earlier chapters covered how the checker compares object shapes. Here the question is narrower: what happens when a member of a shape is optional or read-only?
Two modifiers, two different effects
The two modifiers look similar but the checker treats them very differently.
?marks a property as possibly absent. It changes assignability in both directions.readonlymarks a property as not writable through that type. It does not change assignability at all for ordinary properties.
Keeping this split in mind explains most of the surprises below.
Optional properties
A property declared with ? may be missing from a value. An object that omits it still satisfies the type.
interface Config {
host: string;
port?: number;
}
const a: Config = { host: "localhost" };
const b: Config = { host: "localhost", port: 8080 };
function portOf(c: Config): number {
// c.port has type number | undefined, so we must handle undefined
return c.port ?? 80;
}
console.log(portOf(a), portOf(b)); // 80 8080With strictNullChecks on (part of strict), reading an optional property gives T | undefined. The checker forces you to deal with the missing case before using the value as T.
Optional to required is an error
The rule has a direction. A target with an optional property accepts sources that have the property, lack it, or have it optional. A target with a required property accepts only sources where that property is definitely present.
interface Draft {
title: string;
body?: string;
}
interface Published {
title: string;
body: string;
}
declare const draft: Draft;
declare const published: Published;
const p: Published = draft;
// Error: Property 'body' is optional in type 'Draft'
// but required in type 'Published'.
const d: Draft = published; // OK: body is always present, which satisfies "maybe present"This follows from the idea of substitutability. Any code written for Draft already handles a missing body, so a Published value is safe there. Code written for Published assumes body is a string, so a Draft could break it.
Optional means "or undefined", unless you opt out
By default, port?: number behaves like port?: number | undefined. Explicitly assigning undefined is allowed, and a source with port: number | undefined is assignable to the target.
interface Opts {
retries?: number;
}
const explicit: Opts = { retries: undefined }; // OK by defaultThat hides a real difference at runtime. {} and { retries: undefined } are different objects: "retries" in obj and Object.keys(obj) give different answers, and a spread such as { ...defaults, ...opts } will overwrite a default with undefined.
The exactOptionalPropertyTypes compiler option closes this gap. It is not part of strict, so you must turn it on yourself.
// tsconfig: "strict": true, "exactOptionalPropertyTypes": true
interface Opts {
retries?: number;
}
const ok: Opts = {};
const bad: Opts = { retries: undefined };
// Error: Type 'undefined' is not assignable to type 'number'
// with 'exactOptionalPropertyTypes: true'.Under this option, retries?: number means "absent or a number". To allow an explicit undefined, write retries?: number | undefined. Reading the property still gives number | undefined, so only the writing side changes.
Readonly properties
readonly stops writes through a given type. The compiler rejects direct assignment to the property.
interface Frozen {
readonly id: string;
}
const f: Frozen = { id: "a" };
f.id = "b";
// Error: Cannot assign to 'id' because it is a read-only property.Readonly does not affect assignability
This is the part that surprises people. A Frozen value can be assigned to a type with a mutable id, and the checker raises no complaint.
interface Frozen {
readonly id: string;
}
interface Mutable {
id: string;
}
const f: Frozen = { id: "a" };
const m: Mutable = f; // OK: readonly is not part of the compatibility check
m.id = "b";
console.log(f.id); // "b"The reason is practical. Requiring exact readonly matches would break a great deal of existing JavaScript-style code, such as passing a read-only object to a function that never writes to it but declares its parameter without readonly. So readonly is a promise made at one access point, not a property of the value. Another reference to the same object can still write.
Arrays are the exception
Arrays and tuples are handled differently. readonly number[] lacks methods such as push and sort, so it is a genuinely different shape from number[], and the assignment is rejected.
const ro: readonly number[] = [1, 2, 3];
const rw: number[] = ro;
// Error: The type 'readonly number[]' is 'readonly' and cannot be
// assigned to the mutable type 'number[]'.
const arr: number[] = [1, 2, 3];
const view: readonly number[] = arr; // OK: a mutable array is a valid read-only viewThe safe direction is mutable to read-only. Declaring function parameters as readonly T[] is a good habit for functions that only read. It lets callers pass either kind of array, and it documents that the function will not modify its input.
Readonly is shallow
readonly applies to the property itself, not to what it points to.
interface Settings {
readonly tags: string[];
}
const s: Settings = { tags: ["a"] };
s.tags.push("b"); // OK: the array is still mutable
s.tags = [];
// Error: Cannot assign to 'tags' because it is a read-only property.For deep protection you need readonly string[] on the inner type, or a recursive helper type. Also remember that readonly is erased at compile time. It does not freeze anything at runtime. Use Object.freeze if you need that, and note that it is also shallow.
Changing the modifiers with mapped types
The standard library and your own code can add or remove both modifiers across a whole type. A + or - prefix on the modifier controls this.
interface User {
readonly id: string;
name?: string;
}
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Complete<T> = { [K in keyof T]-?: T[K] };
type EditableUser = Mutable<User>; // { id: string; name?: string }
type FullUser = Complete<User>; // { readonly id: string; name: string }The built-in Partial<T>, Required<T>, and Readonly<T> are the same idea with a fixed choice of modifier. Because the results are ordinary object shapes, they take part in assignability like any other type. For example, Required<User> is not assignable from User, for the same optional-to-required reason shown earlier.
Interaction with other structural rules
Optional properties interact with two checks covered in neighbouring chapters.
- Excess property checks. A fresh object literal is checked against the target's known properties, and optional ones count as known. Misspelling an optional name in an inline literal is therefore caught.
- Weak types. If every property of the target is optional, the source must share at least one property with it. This catches
{ colour: "red" }being passed where{ color?: string }is expected.
A property that is optional in the target and absent from the source is never an error by itself. The errors arise from the weak type rule, the excess property rule, or a type mismatch on a property that is present.
Summary of the rules
| Situation | Assignable? | Why |
|---|---|---|
| Source lacks property, target has it optional | Yes | The target allows absence |
| Source lacks property, target has it required | No | The property would be missing |
| Source optional, target required | No | The value might be undefined or absent |
| Source required, target optional | Yes | Present is a valid case of maybe present |
| Source `readonly`, target mutable (objects) | Yes | `readonly` is not checked for properties |
| Source `readonly T[]`, target `T[]` | No | The read-only array type lacks the mutating methods |
| Source `T[]`, target `readonly T[]` | Yes | A mutable array can serve as a read-only view |
| Source `{ p: undefined }`, target `{ p?: number }` | Yes by default, no with `exactOptionalPropertyTypes` | The option separates absent from undefined |
Common mistakes
- Treating
readonlyas immutability. It blocks writes through one type only. Aliases with mutable types and nested objects can still change. - Using
?where| undefinedis meant. A required property with a possibly-undefined value (name: string | undefined) forces callers to write the key. An optional one lets them omit it. Choose based on whether the key should be present. - Assuming optional means safe to omit everywhere. Passing an optional-property source to a function that requires the property is an error, so partially filled objects need to be completed or checked first.
- Spreading partial objects over defaults.
{ ...defaults, ...partial }can yieldundefinedfor a key ifpartialcarries an explicitundefined, and the compiler accepts this unlessexactOptionalPropertyTypesis on.
Exercise
Given interface A { readonly x: number; y?: string } and interface B { x: number; y: string }, which of const b: B = a and const a2: A = b compile, where a: A and b: B are existing variables? Explain each result.
Show answer
const b: B = a does not compile. y is optional in A but required in B, so a.y could be missing. The readonly on x is not the problem, because readonly is ignored in this check. const a2: A = b compiles. B always has x and y, which satisfies A's required x and optional y, and a mutable x can be assigned to a readonly one.
Exercise
A function function total(values: number[]): number only reads its argument. A caller holds const data: readonly number[] = [1, 2, 3] and gets an error calling total(data). What change to the function's signature fixes this without a cast, and why is it correct?
Show answer
Change the parameter to values: readonly number[]. A readonly number[] cannot be assigned to number[] because the mutable type includes methods like push that the read-only type lacks. Both number[] and readonly number[] are assignable to readonly number[], so every caller works, and the signature states that the function will not modify the array.