Object Shapes, Optional, and Readonly Properties

Object types define the properties and their types. A ? marks a property as optional, which means it may be absent (and under strict null checks, reading it can produce undefined). readonly prevents assignment through that particular typed reference, but it is not a deep runtime freeze and does not guarantee that another alias cannot mutate the same object.

Use optional properties when absence is meaningful. If a value has distinct states with different required fields, a discriminated union is often clearer than one object containing many optional fields.

A typed settings object
type Profile = {
  readonly id: string;
  name: string;
  bio?: string;
};

const profile: Profile = { id: "p-1", name: "Mira" };
profile.name = "Mira S.";
// profile.id = "p-2"; // Error
💡 bio may be omitted, name can change, and id cannot be reassigned through this reference. readonly is a type-system restriction, not Object.freeze.
Key Takeaways
  • Use optional properties only when absence is valid.
  • readonly prevents assignment through a typed reference.
  • Model mutually exclusive states with unions when appropriate.
Knowledge Check

What does `bio?: string` mean?