Syncing account progress…

Back

Beginner · 10 min

Readonly data

Prevent accidental writes through a type and create updated copies.

Protect a property

readonly prevents assignment through that typed reference. It is a compile-time restriction, not a runtime freeze, and nested values need their own protection.

type User = { readonly id: number; name: string };
const user: User = { id: 1, name: "Ada" };
user.name = "Mina";
console.log(user.id + ": " + user.name);

Output

1: Mina

Copy before changing

A readonly array supports reads but not mutating methods such as push(). Spread its elements into a new array when you need an updated collection.

const original: readonly number[] = [2, 4];
const updated = [...original, 6];
console.log(original.length + ": " + updated.length);

Output

2: 3

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Complete the task, then check your understanding with the practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Create an updated array

Create "updated" by adding 6 to a copy of "original". Keep the readonly annotation and display both lengths.

Practice