readonly Properties and Parameter Properties
Use readonly and shorthand constructor properties.
Welcome
readonly prevents properties from being changed after initialization. Parameter properties combine declaration and initialization into a single constructor line.
readonly on Class Properties
Declare a property readonly to allow setting it once (in the constructor) but prevent later changes.
class Invoice {
readonly invoiceId: string;
constructor(id: string) { this.invoiceId = id; }
}
const inv = new Invoice('INV-001');
// inv.invoiceId = 'INV-002'; // Error!All lessons in this course
- TypeScript Classes and Constructors
- public, private, and protected Modifiers
- readonly Properties and Parameter Properties
- Implementing Interfaces with Classes