Recall & Review
beginner
What does the <code>readonly</code> keyword do in a TypeScript class property?It makes the property value unchangeable after it is initialized, preventing any reassignment.
Click to reveal answer
beginner
Can a
readonly property be assigned a value inside the constructor?Yes,
readonly properties can be assigned or modified inside the constructor but not outside of it.Click to reveal answer
beginner
What happens if you try to assign a new value to a
readonly property outside the constructor?TypeScript will show a compile-time error preventing the reassignment.
Click to reveal answer
beginner
Example: <pre>class Car { readonly model: string; constructor(model: string) { this.model = model; } }</pre> Can you change <code>model</code> after creating a <code>Car</code> object?No, once the
model is set in the constructor, it cannot be changed later because it is readonly.Click to reveal answer
beginner
Why use
readonly properties in classes?To protect important data from accidental changes and make the code safer and easier to understand.
Click to reveal answer
What is true about a
readonly property in TypeScript?✗ Incorrect
A
readonly property can be assigned once, usually in the constructor, and cannot be changed later.Where can you assign a value to a
readonly property?✗ Incorrect
You can assign or modify a
readonly property inside the constructor.What error occurs if you try to change a
readonly property after construction?✗ Incorrect
TypeScript prevents reassignment of
readonly properties with a compile-time error.Which keyword makes a class property immutable after initialization?
✗ Incorrect
readonly makes a property immutable after it is initialized.Why might you choose
readonly over private?✗ Incorrect
readonly lets others read the property but stops them from changing it, unlike private which restricts access.Explain how
readonly properties work in TypeScript classes and when you can assign their values.Think about when and where you can set the value and what happens if you try to change it later.
You got /4 concepts.
Describe a real-life example where using
readonly properties in a class would be helpful.Imagine something that should never change once set, like a serial number or birthdate.
You got /4 concepts.