Optional and readonly Properties
Mark properties that may be missing with ?, and protect properties from changing with readonly.
What you will learn
- Make a property optional with ?
- Protect a property with readonly
- Combine both in a realistic shape
Optional properties with ?
Not every property is always present. A ? after a property name means it is optional — an object can include it or leave it out.
interface Profile {
name: string;
bio?: string; // optional
}
const a: Profile = { name: 'Asha' }; // no bio — fine
const b: Profile = { name: 'Ben', bio: 'Coder' }; // bio present — fine
console.log(a.name, b.bio);Note: Output:
Asha Coder
Both objects are valid: bio may be present or absent. Inside code, bio has type string | undefined, so check it before use.
readonly — set once, never change
A readonly property can be set when the object is created but cannot be changed afterwards. Perfect for things like an id that should never move.
interface Account {
readonly id: number;
balance: number;
}
const acc: Account = { id: 1, balance: 500 };
acc.balance = 600; // ok — balance can change
acc.id = 2; // error — id is readonlyNote: Output:
Error: Cannot assign to 'id' because it is a read-only property.
balance changed happily, but id is protected. This prevents accidental edits to values that must stay fixed.
Both together in a real shape
interface Product {
readonly sku: string; // never changes
name: string;
discount?: number; // may not exist
}
const item: Product = { sku: 'KBD-01', name: 'Keyboard' };
console.log(item.sku, item.discount ?? 'no discount');Note: Output:
KBD-01 no discount
sku is fixed forever; discount was left out, so ?? 'no discount' supplies a fallback. This shape is both safe and flexible.
Tip: Use readonly for identifiers and config that should never change after creation. Use ? for properties that are genuinely sometimes absent.
Watch out: readonly is checked by TypeScript at compile time only. In the final JavaScript the property is a normal field — the protection is during development, which is exactly when it helps.
Q. What does readonly do to a property?
✍️ Practice
- Add an optional
nickname?: stringto aUserinterface and create users with and without it. - Give a
Ticketinterface areadonly id: numberand try to change it after creation.
🏠 Homework
- Design an
Orderinterface with a readonly orderId, a required total, and an optional couponCode, then build a valid order object.