Module 28: Interfaces and Type Design

Lesson 2 of 5 · 15–25 minutes

Optional and readonly properties

🏠The everyday picture

On a form, some boxes are marked "optional" (a landline number) and some are filled in by the office only, never changed by the applicant (the application number).

📘What it really is

interface Customer {
  id: string;
  name: string;
  email?: string;
}

customer.email has the type string | undefined, so TypeScript makes you handle the missing case.

interface Order {
  readonly id: string;
  readonly createdAt: string;
  status: Status;
}

Trying order.id = "X" is an error. Use it for things that must never change, like ids and creation times.

🖱️Try it

Make id and createdAt readonly in an Order interface, email optional in Customer, and try to change an order's id and to call .toLowerCase() on a customer's email without checking it. Read both errors. Fix the email code with a check or ?..

✅Quick check

Why make an order's id readonly?

Show the answer

Ids must never change once created; readonly makes changing one an error.

Every customer must have a phone number. Should phone be optional?

Show the answer

No. Make it required so every customer object must include it.

← PreviousInterfaces
ProLearners Assist