Ad space (banner)
Lesson 19 / 20

The readonly Modifier

This lesson covers the readonly modifier, used to prevent a value from being changed once it's set. It's for anyone searching "TypeScript readonly usage."

Adding readonly before a property means that property can only be set at initialization (like inside a constructor); trying to rewrite it afterward produces a compile error.

The example marks a setting value that shouldn't change once it's decided, using interface Config { readonly apiKey: string; }.

A common early mistake is not realizing "readonly can sometimes still be changed at runtime, even with it set." readonly is strictly a TypeScript compile-time check โ€” once converted to JavaScript, it behaves just like an ordinary property. If you need to fully prevent a change, you'll need to combine it with a different mechanism.

In real projects, marking values that "shouldn't change once decided" โ€” an API key, an ID, a creation timestamp โ€” with readonly helps prevent careless bugs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)