typescript · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A locked serial number. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Phone { readonly serial: string; owner: string }
const phone: Phone = { serial: "X9-200", owner: "Ben" };
phone.owner = "Cara";
phone.serial = "X9-201";
console.log(phone.owner, phone.serial);
your turn
Your turn. Lock the library book's number.
Put readonly in front of the property that should never change. Then lend the book to someone new and run it.
fix it
More guests are coming, but the list is locked. Fix it!
- Read the error:
TS2339: Property 'push' does not exist on type 'readonly string[]'. - This list needs to grow, so it should not be locked. Look at the label on line 1.
- Remove
readonlyfrom the label on line 1, so it saysstring[], then press run.
nailed it
you can lock what must not change. :D
readonlystops a property from ever getting a new value.- A
readonlyarray can be read but never changed. - The lock is checked before your code runs.
new words in your collection
- readonly
This lesson isn’t saved. A free account remembers every lesson you finish.