BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🔒

Optional and Readonly Properties: Fields That Bend or Lock

💡 Use ? to let a property be absent and readonly to forbid reassigning it after creation — both enforced only at compile time.

Recall from the previous card that an interface describes the shape of an object. But real data is messier than a rigid shape — sometimes a field is missing, and sometimes a field should never change after creation. TypeScript gives you two modifiers for exactly this: ? for optional and readonly for immutable.

Add a ? after a property name to make it optional. The object is valid whether or not that field is present, and its type becomes T | undefined. This is perfect for things like a middle name or an unset preference.

ts
interface User {
  id: number;
  name: string;
  nickname?: string; // optional
}

const a: User = { id: 1, name: "Ada" };          // ok, no nickname
const b: User = { id: 2, name: "Bo", nickname: "B" }; // also ok

Mark a property readonly to lock it after the object is built. You can still read it freely, but any attempt to reassign it is a compile-time error — great for IDs and other values that must stay stable.

ts
interface Account {
  readonly id: number;
  balance: number;
}

const acc: Account = { id: 100, balance: 50 };
acc.balance = 75;   // ok
acc.id = 101;       // Error: Cannot assign to 'id' because it is read-only

Two important nuances: readonly is enforced only by the type checker (it disappears at runtime, so it's not deep immutability), and ? differs from a property explicitly typed string | undefined — with ? you may omit the key entirely, while a required string | undefined field must still be present.

🔒 Optional and Readonly Properties: Fields That Bend or Lock — BeCuriouz