- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
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.
๐งช 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).
