Object types, optional and readonly properties

Beginner · 10 min

Describing the shape of an object, marking properties that may be absent with `?`, and properties that must not be reassigned with `readonly`.

Before thisType annotations and type inference

Hitesh Choudhary · 10 min

Object types, optional and readonly properties

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Hitesh ChoudharyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An object type lists property names and their types, such as `{ id: number; name: string }`, and a value must have every required property with the right type to match.
  • A `?` after a property name makes it optional; the property may be missing, and reading it gives `T | undefined`, which the compiler makes you handle before use.
  • A `readonly` modifier forbids reassigning that property after the object is created, but it is a compile-time check only and it is shallow; nested objects stay mutable.
  • Giving an object type a name with `type User = { ... }` lets many values and functions share one definition instead of repeating the shape inline.

Objects carry most of your data

Most values in a real program are objects: a user, an order, a config, an API response. A bug with an object rarely looks like “this whole thing is the wrong type”. It looks like a missing field, a misspelled one, or a field that was quietly overwritten somewhere it shouldn’t have been. Object types exist to catch exactly those three.

Writing an object type

An object type lists properties and the type of each:

let user: { id: number; name: string; email: string } = {
  id: 1,
  name: "Ada",
  email: "ada@example.com",
};

Properties are separated by semicolons or commas; both work. Writing the shape inline gets tedious once a second variable or function needs it, so give it a name with a type alias:

type User = {
  id: number;
  name: string;
  email: string;
};

const ada: User = { id: 1, name: "Ada", email: "ada@example.com" };

const grace: User = { id: 2, name: "Grace" };
// Error: Property 'email' is missing in type '{ id: number; name: string; }' but required in type 'User'.

A type alias is one of two ways to name a shape; interface is the other, and the type aliases vs interfaces lesson compares them. Either works for everything in this lesson.

Inference applies to objects too. const point = { x: 1, y: 2 } is already typed { x: number; y: number }, and point.z is an error. The annotation matters when you want a value checked against an agreed shape, especially one that crosses a function or module boundary.

Optional properties

Not every field is always present. A user may or may not have a nickname. Mark that with ? after the name:

type Profile = {
  name: string;
  nickname?: string;
};

const a: Profile = { name: "Ada" }; // fine, nickname omitted
const b: Profile = { name: "Grace", nickname: "Amazing Grace" }; // fine

The catch comes when you read it. An optional property might not be there, so its type when read is string | undefined:

function greet(p: Profile) {
  return p.nickname.toUpperCase(); // Error: 'p.nickname' is possibly 'undefined'.
}

function greetSafely(p: Profile) {
  return p.nickname?.toUpperCase() ?? p.name;
}

The compiler won’t let you treat a maybe-missing value as definitely present. Checking with if (p.nickname), or using ?. and ?? as above, satisfies it. Those checks are a form of narrowing, which has a group of its own, and the full story of undefined is in the strict null checks lesson.

Use ? for data that is genuinely absent sometimes. Don’t use it to dodge an error about a missing field that should always be there; that only moves the problem to every place that reads it.

Readonly properties

Some fields should never change after an object is created: an id, a createdAt timestamp. The readonly modifier says so:

type Order = {
  readonly id: string;
  readonly createdAt: Date;
  status: string;
};

const order: Order = { id: "o-17", createdAt: new Date(), status: "open" };

order.status = "shipped"; // fine
order.id = "o-18"; // Error: Cannot assign to 'id' because it is a read-only property.

Think of readonly like a serial number stamped on a machine. You can repaint the machine and change its settings, but the stamp is not editable. Two limits are worth knowing from the start.

It is compile-time only. Like every type, it is erased. The emitted JavaScript will happily reassign id if some untyped code does it. If you need runtime protection, Object.freeze gives it.

It is shallow. readonly protects the property, not the object the property points to:

type Account = {
  readonly owner: { name: string };
};

const acct: Account = { owner: { name: "Ada" } };

acct.owner = { name: "Grace" }; // Error: Cannot assign to 'owner' because it is a read-only property.
acct.owner.name = "Grace"; // fine, the nested object is mutable

createdAt above has the same gap: you cannot replace the Date, but order.createdAt.setFullYear(1999) compiles. Making things read-only all the way down, with Readonly<T>, read-only arrays, and as const, is the subject of the next lesson.

Combining the two

The modifiers stack: readonly middleName?: string is a property that may be absent and, if present, cannot be reassigned. That combination is common for configuration objects, where fields are optional and nothing should modify the config once it is loaded.

One more behaviour you will notice: passing an object literal with an extra, unknown property to a typed variable is an error, even though objects with extra properties are usually accepted elsewhere. That rule, excess property checking, belongs to structural typing, later in the roadmap.

About the video

Hitesh Choudhary’s video builds object types up step by step, then adds readonly and optional properties and shows the editor errors each one produces. The pace is relaxed and the explanations are clear, and although it is from 2022, nothing it shows has changed. It treats readonly mainly as a way to block reassignment; the shallowness and the compile-time-only nature described above are worth keeping in mind as you watch. Jack Herrington’s video in the links focuses on the optional side, including optional chaining.

Check yourself

  1. 01A type has `nickname?: string`. Why does `user.nickname.toUpperCase()` fail to compile?

    An optional property can be missing, so reading it gives `string | undefined`. Calling a method on a value that might be `undefined` would crash at runtime, so the compiler reports that `user.nickname` is possibly `undefined`. Check it first or use optional chaining.

  2. 02Does `readonly id: number` stop JavaScript from changing `id` at runtime?

    No. The modifier is erased with all other types, so the emitted JavaScript has no protection. It stops your TypeScript code from compiling an assignment to `id`. If you need runtime protection, `Object.freeze` provides it.

  3. 03If an object type has `readonly address: { city: string }`, can you write `user.address.city = "Oslo"`?

    Yes. `readonly` applies only to the `address` property itself, so you cannot replace the whole address object, but the object it points to is still mutable. Each nested property needs its own `readonly`, or a deep read-only approach from the next lesson.

  4. 04What is the difference between leaving a required property out of an object literal and setting it to `undefined`?

    Leaving it out reports "Property is missing". Setting a required `string` property to `undefined` reports that `undefined` is not assignable to `string`. Both fail; only marking the property optional with `?` permits it to be absent.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark