Sub topic 4
Optional and readonly properties
This chapter assumes you can write basic interfaces and type aliases, and that you know TypeScript's primitive types, arrays, and strict mode. Two modifiers change what a property means in a shape: ? makes a property optional, and readonly makes it unassignable after the object is created. Both work the same way in interfaces and type aliases.
Optional properties
A property followed by ? may be missing from the object. When you read it, TypeScript gives you the declared type plus undefined.
interface User {
readonly id: number;
name: string;
email?: string;
}
const a: User = { id: 1, name: "Ada" };
const b: User = { id: 2, name: "Grace", email: "[email protected]" };
function contact(user: User): string {
// user.email has type string | undefined here
return user.email ?? "no email on file";
}
console.log(contact(a)); // no email on file
console.log(contact(b)); // [email protected]Because the property type includes undefined, the compiler forces you to handle the missing case before you call string methods on it.
interface User {
name: string;
email?: string;
}
function domain(user: User): string {
// return user.email.split("@")[1]; // error: 'user.email' is possibly 'undefined'
if (user.email === undefined) {
return "unknown";
}
return user.email.split("@")[1];
}The same syntax works in a type alias.
type Options = {
verbose?: boolean;
retries?: number;
};
const defaults: Options = {};Optional versus `| undefined`
email?: string and email: string | undefined look similar but are different requirements.
- With
email?: string, the key may be left out entirely. - With
email: string | undefined, the key must be present, although its value may beundefined.
interface A {
email?: string;
}
interface B {
email: string | undefined;
}
const ok1: A = {};
const ok2: B = { email: undefined };
// const bad: B = {}; // error: Property 'email' is missing in type '{}' but required in type 'B'.Use ? when callers may omit the key. Use | undefined when you want callers to state explicitly that there is no value, for example to prevent a forgotten argument.
exactOptionalPropertyTypes
By default, email?: string also accepts an explicit email: undefined. The compiler option exactOptionalPropertyTypes tightens this. With it enabled, an optional property may be omitted but cannot be assigned undefined unless you write email?: string | undefined.
// tsconfig: { "compilerOptions": { "strict": true, "exactOptionalPropertyTypes": true } }
interface Profile {
nickname?: string;
}
const p1: Profile = {}; // allowed
// const p2: Profile = { nickname: undefined }; // error with exactOptionalPropertyTypesThis option is not part of strict. You must turn it on separately. It matters when code distinguishes "key absent" from "key set to undefined", as Object.keys, in checks, and JSON serialization do.
Readonly properties
readonly marks a property that can be set when the object is created but not reassigned afterward.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
// p.x = 10; // error: Cannot assign to 'x' because it is a read-only property.
function move(p: Point, dx: number): Point {
return { x: p.x + dx, y: p.y }; // build a new object instead of mutating
}Readonly objects push you toward creating updated copies rather than changing values in place. That makes code easier to reason about when several parts of a program share one object.
What readonly does not do
readonly is checked only at compile time, and it is shallow. Two consequences follow.
- At runtime nothing is frozen. The compiled JavaScript has no
readonlyat all, so code that bypasses the type system can still change the value. - It applies only to the property itself, not to what the property refers to.
interface Team {
readonly members: string[];
readonly lead: { name: string };
}
const team: Team = { members: ["Ada"], lead: { name: "Grace" } };
// team.members = []; // error: members is read-only
team.members.push("Linus"); // allowed: the array itself is mutable
team.lead.name = "Alan"; // allowed: the nested object is mutableTo protect the contents, use a readonly array type, such as readonly string[] or ReadonlyArray<string>, and mark nested properties readonly too.
interface SafeTeam {
readonly members: readonly string[];
readonly lead: { readonly name: string };
}
const safe: SafeTeam = { members: ["Ada"], lead: { name: "Grace" } };
// safe.members.push("Linus"); // error: Property 'push' does not exist on type 'readonly string[]'.
// safe.lead.name = "Alan"; // error: Cannot assign to 'name' because it is a read-only property.If you need real runtime protection, call Object.freeze. It is also shallow, so freeze nested objects yourself if they matter.
Readonly is not enforced between compatible types
TypeScript compares shapes structurally, and it does not treat readonly as part of compatibility for plain properties. A mutable object can be assigned to a readonly shape, and the reverse also compiles.
interface ReadonlyPoint {
readonly x: number;
}
interface MutablePoint {
x: number;
}
const ro: ReadonlyPoint = { x: 1 };
const mu: MutablePoint = ro; // compiles, even though mu.x can now change the same object
mu.x = 99;
console.log(ro.x); // 99This is a known gap. Treat readonly as a guard against accidental assignment through that particular name, not as a guarantee that the value never changes. Readonly arrays are stricter: a readonly string[] cannot be assigned to a string[].
Combining the modifiers
A property can be both optional and readonly. The order is readonly first, then the name, then ?.
interface Settings {
readonly theme?: "light" | "dark";
}
const s: Settings = {};
// s.theme = "dark"; // error: Cannot assign to 'theme' because it is a read-only property.An optional readonly property is useful for configuration values that callers may provide at construction but nobody may change later.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `'x' is possibly 'undefined'` | Reading an optional property without checking it | Narrow with `if`, or use `??` or `?.` | |
| `Property 'x' is missing in type` | The property is required, or typed `T \ | undefined` without `?` | Add the key, or declare it with `?` |
| `Cannot assign to 'x' because it is a read-only property` | Assigning to a `readonly` property | Create a new object, or remove `readonly` if mutation is intended | |
| Array still changes after `readonly` | `readonly` guards the reference, not the contents | Use `readonly T[]` | |
| `{ key: undefined }` rejected | `exactOptionalPropertyTypes` is on | Declare `key?: T \ | undefined` |
Optional properties and object literals
Excess property checks apply to fresh object literals. If you misspell an optional property, the compiler reports it, because the typo is not part of the shape.
interface Options {
retries?: number;
}
// const o: Options = { retires: 3 }; // error: 'retires' does not exist in type 'Options'. Did you mean 'retries'?
const raw = { retires: 3 };
const o2: Options = raw; // no error for a non-literal. See the weak type note below.A type whose properties are all optional is called a weak type. TypeScript refuses to assign a value to a weak type when the two share no properties at all, so raw above would normally be reported with "has no properties in common". If you see that message, it usually means a name is misspelled or the wrong object was passed.
Summary of rules
- Use
?when a key may be absent. ExpectT | undefinedwhen you read it. - Use
| undefinedwithout?when the key must be present. - Turn on
exactOptionalPropertyTypesif you need to tell an absent key from anundefinedvalue. - Use
readonlyto prevent reassignment through a name. Remember it is shallow and compile-time only. - Use
readonly T[]and nestedreadonlyfor deeper protection.
Exercise
Given interface Job { readonly id: string; tags: string[]; retries?: number }, and const job: Job = { id: "a", tags: [] };, which of these lines compile: (1) job.id = "b"; (2) job.tags.push("x"); (3) job.retries = job.retries + 1;? Explain each result with strict mode on.
Show answer
(1) Does not compile, because id is readonly. (2) Compiles, because readonly is not applied to tags, and even if it were, it would only prevent reassigning the reference. (3) Does not compile, because job.retries has type number | undefined, so adding 1 is an error ("possibly 'undefined'"). A fix is job.retries = (job.retries ?? 0) + 1;.
Exercise
What is the difference between { email?: string } and { email: string | undefined }, and when would you pick each?
Show answer
With email?: string the key may be left out of the object. With email: string | undefined the key must be present but may hold undefined. Pick ? when callers may omit the value. Pick string | undefined when you want callers to state explicitly that no value exists, so a forgotten field becomes a compile error.
Exercise
Why does const mu: { x: number } = ro; compile when ro is typed { readonly x: number }, and what does this tell you about relying on readonly?
Show answer
TypeScript checks compatibility structurally and ignores readonly on properties when comparing types. So a readonly-typed value can be assigned to a mutable-typed name, and changes made through that name are visible through the original. readonly therefore protects only against assignment through that particular typed reference. It is not a guarantee of immutability.