Typescript Foundations / Objects & Interfaces

Optional & Readonly properties

πŸ‘‰ Use ? to make a property optional β€” the object may or may not include it.

interface User {
  name: string;
  age?: number;  // optional
}

const user1: User = { name: "Tisha" };           // βœ… OK
const user2: User = { name: "Tisha", age: 21 };  // βœ… OK

🧠 You must handle the case where the property is undefined:

function printAge(user: User) {
  if (user.age !== undefined) {
    console.log(`Age: ${user.age}`);
  } else {
    console.log("Age not provided.");
  }
}

🌟 Readonly Properties (readonly)

πŸ‘‰ Use readonly to prevent a property from being reassigned after initialization.

interface Config {
  readonly id: string;
  theme: string;
}

const appConfig: Config = {
  id: "abc123",
  theme: "dark"
};

appConfig.theme = "light";   // βœ… OK
// appConfig.id = "newId";   
// ❌ Error: Cannot assign to 'id' because it is a  read-only property

βœ… You can combine both!

interface Product {
  readonly sku: string;
  name: string;
  price?: number; // optional
}

const item: Product = {
  sku: "P123",
  name: "Notebook"
};

// item.sku = "P124"; ❌ Error

πŸ”₯ Use Cases

Modifier

Purpose

Common Use Case

? optional

Property may be left out

Optional fields in forms or APIs

readonly

Property can't be reassigned after set

IDs, constants, system config values


🧠 Note

  • readonly only works on the first level β€” nested objects can still be modified unless their properties are also marked readonly.

  • Use Readonly<T> utility type to make entire objects immutable.

type ImmutableUser = Readonly<{
  name: string;
  age: number;
}>;

const user: ImmutableUser = { name: "Tisha", age: 21 };
// user.name = "Riya"; // ❌ Error

βœ… Summary

Modifier

Syntax

Effect

Optional

prop?: type

Can be undefined or omitted

Readonly

readonly prop: type

Cannot be reassigned after initialization