Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 4 of 8
Optional, Readonly & Non-Null Assertion
`optional` (`?`) marks a property or parameter as possibly absent. `readonly` prevents mutation after assignment. The non-null assertion (`!`) tells TypeScript you know a value isn't null - use it sparingly. Together they model immutable data, optional configuration, and API responses precisely.
Optional, Readonly & Assertion Operators
// ── Optional properties ───────────────────────────────────────
interface TaskOptions {
title: string;
description?: string; // string | undefined
dueDate?: Date; // Date | undefined
tags?: string[]; // string[] | undefined
}
function createTask(opts: TaskOptions): Task {
return {
id: Date.now(),
title: opts.title,
description: opts.description ?? null,
dueDate: opts.dueDate ?? null,
tags: opts.tags ?? [],
status: "todo",
priority: "medium",
assignee: null,
createdAt: new Date(),
updatedAt: new Date(),
};
}
createTask({ title: "Write docs" }); // ✅ optional fields omitted
// ── Optional vs undefined union ────────────────────────────────
interface A { field?: string } // field can be absent
interface B { field: string | undefined } // field must be present, can be undefined
// With exactOptionalPropertyTypes: true in tsconfig,
// these are strictly different. Prefer optional (?) for truly absent fields.
// ── Readonly modifier ──────────────────────────────────────────
interface ImmutableTask {
readonly id: number; // cannot reassign after creation
readonly createdAt: Date;
title: string; // mutable - title can change
}
const task: ImmutableTask = { id: 1, createdAt: new Date(), title: "Launch" };
task.title = "Launch v2"; // ✅ mutable field
task.id = 2; // ❌ Error: Cannot assign to 'id'
// Readonly arrays - prevent push/pop/splice:
const tags: readonly string[] = ["design", "backend"];
tags.push("api"); // ❌ Error: push does not exist on readonly
// ── Readonly utility type ─────────────────────────────────────
type ReadonlyTask = Readonly<Task>;
// All properties become readonly - useful for "frozen" domain objects
// ── Non-null assertion (!) - use sparingly ───────────────────
// Tells TS "I guarantee this is not null or undefined"
const element = document.getElementById("app");
// Type: HTMLElement | null ← TS doesn't know if element exists
element!.style.color = "red"; // ✅ bypasses null check
// But: if element IS null at runtime → crash! Use with care.
// ── Better alternative to ! - explicit check ──────────────────
if (element !== null) {
element.style.color = "red"; // ✅ runtime-safe narrowing
}
// ── Legitimate ! use case - post-assertion after known init ───
class AppController {
private db!: Database; // initialised in init(), not constructor
async init(): Promise<void> {
this.db = await connectDb();
}
// The ! tells TS: "I know this will be set before use"
}Visual architecture and concepts for Optional, Readonly & Non-Null Assertion
Common Mistakes
- Overusing `!` - every `!` is a promise you make to TypeScript that you might break at runtime. Prefer explicit null checks or optional chaining (`?.`).
- Treating `readonly` as deep immutability - `readonly id: number[]` prevents reassigning the array, but NOT pushing to it. For deep immutability, use `readonly number[]` or `ReadonlyArray<number>`.
- Confusing `field?: T` with `field: T | undefined` - with `exactOptionalPropertyTypes` enabled, these differ. An optional field can be entirely absent from the object; the union field must be present (just possibly `undefined`).
Key Takeaways
- `optional` (`.
- Overusing `!` - every `!` is a promise you make to TypeScript that you might break at runtime. Prefer explicit null checks or optional chaining (`?.`).
- Treating `readonly` as deep immutability - `readonly id: number[]` prevents reassigning the array, but NOT pushing to it. For deep immutability, use `readonly number[]` or `ReadonlyArray<number>`.
- Confusing `field?: T` with `field: T | undefined` - with `exactOptionalPropertyTypes` enabled, these differ. An optional field can be entirely absent from the object; the union field must be present (just possibly `undefined`).
Finished this lesson?