Complete the code to declare a readonly property in a TypeScript class.
class Person { readonly name: string; constructor(name: string) { this.[1] = name; } }
readonly keyword in the constructor assignment.The readonly property name is assigned inside the constructor using this.name = name;.
Complete the code to prevent modification of a readonly property after initialization.
class Car { readonly model: string; constructor(model: string) { this.model = model; } changeModel(newModel: string) { // This line should cause an error this.model [1] newModel; } }
Assigning a new value to a readonly property like this.model = newModel; causes a TypeScript error.
Fix the error in the class by correctly declaring a readonly property with an initial value.
class Book { [1] title: string = "Unknown"; }
const inside a class property declaration.private with readonly.The readonly keyword declares a property that cannot be changed after initialization.
Fill both blanks to create a readonly property with a default value and a method to read it.
class User { [1] id: number = 0; getId() { return this.[2]; } }
private instead of readonly.The property id is declared readonly and returned by the getId method.
Fill all three blanks to declare a readonly property, initialize it via constructor shorthand, and access it in a method.
class Product { constructor([1] readonly [2]: string) {} display() { console.log(this.[3]); } }
The constructor uses shorthand to declare a readonly property productName. The display method accesses it with this.productName.