Module 28: Interfaces and Type Design
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
- Optional properties may be absent, marked with
?:
interface Customer {
id: string;
name: string;
email?: string;
}
customer.email has the type string | undefined, so TypeScript makes you handle the missing case.
- Readonly properties can't be changed after the object is created:
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.
readonly string[](orReadonlyArray<string>) preventspush,popandsorton an array.-
Be honest about optional. Marking things optional "just in case" spreads checks everywhere. If every customer must have a phone number, make it required.
-
Readonly is a check while writing code; it doesn't freeze the object at runtime.
🖱️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.
