AI Hints
Home›TypeScript Tutorial›Object Types
TypeScript · Lesson 21 of 120

readonly

Look, don't touch.

⏱ 2 min read▶ Video at 16:52🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Some properties should never change after an object is made. Like an order's number. The readonly keyword makes TypeScript reject any change.

readonly
From the video: readonly
  • Never changes
  • Like an order number
  • readonly

A readonly id

The order's ID is readonly, but the status isn't. Changing the status is fine. Changing the ID is rejected. Run it. One error, for the ID only.

app.tstypescript
const order: { readonly id: number; status: string } = { id: 1042, status: "packing" };

order.status = "shipped";
order.id = 9999;
Output
app.ts line 4: Cannot assign to 'id' because it is a read-only property.

Good to know

Readonly is only checked by TypeScript, it doesn't freeze the object while running. Use it for IDs, settings, and anything that shouldn't change. Later we'll see readonly arrays too.

keyvalue
Checkedby TypeScript
Runningnot frozen
Use forids, settings
Laterreadonly arrays

Summary

Readonly properties can be read, but never changed. Next, type aliases.

Key takeaways
  • readonly id
  • Changes rejected
  • Compile-time only
Next up: Type Aliases — name a type