×

typescript · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

locks a property so it can never change.

Some facts should never change once set, like an order number or a date of birth. Put readonly before a property in an interface and the checker refuses any new value with TS2540: cannot assign, because it is a read-only property.

Arrays can be locked too. A readonly string[] can be read and looped over, but not changed. It has no push at all, so trying gives TS2339.

Like const, this lock is checked before your code runs, so it stops mistakes early.

interface Order {
  readonly id: number;
  status: string;
}
const order: Order = { id: 1042, status: "packed" };
order.status = "sent";
const days: readonly string[] = ["Mon", "Tue", "Wed"];
console.log(order.id, order.status);
console.log(days.length, days[0]);

const locks the box. readonly locks a property inside the object.