TYPESCRIPT / CHAPTER 03

Object shapes and readonly views

Beginner

Model records without confusing optional fields and immutability.

By the end of this chapter

  • Describe required and optional properties
  • Handle possibly absent values
  • Understand shallow readonly restrictions

The idea

An object type describes required properties and their value types. Optional properties may be absent, so reading one requires handling undefined under strict checking. Structural compatibility means a value can satisfy a contract by having the needed shape rather than inheriting from a named class. Prefer small contracts that expose only the data an operation actually requires.

Readonly restricts assignments through a particular typed view. It does not freeze the runtime object, and readonly on an outer property does not recursively protect the referenced value. Similarly, readonly arrays prevent array writes through that view but do not necessarily protect fields inside their elements. Treat these tools as useful API signals and combine them with disciplined copying when an operation promises to preserve its input.

TypeScript example
type Ticket = { readonly id: number; title: string; owner?: string };
function label(ticket: Ticket): string {
  return ticket.owner ?? "Unassigned";
}
console.log(label({id: 4, title: "Search"}));
Result
Unassigned

The optional owner may be undefined. Nullish coalescing supplies a label, while readonly prevents assigning a new id through this typed parameter.

Try it yourself

Create a readonly record input and return a new record with a revised title.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Why must a function handle undefined when reading owner?: string?