Describing ShapesCore· 30 min read

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.

bio is optional thanks to ?
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.

id is locked with readonly
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 readonly

Note: 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

readonly sku plus an optional discount
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?

Answer: A readonly property can be assigned once (at creation) and then cannot be reassigned. It protects values that should stay fixed, like an id.

✍️ Practice

  1. Add an optional nickname?: string to a User interface and create users with and without it.
  2. Give a Ticket interface a readonly id: number and try to change it after creation.

🏠 Homework

  1. Design an Order interface with a readonly orderId, a required total, and an optional couponCode, then build a valid order object.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →