0
0
Typescriptprogramming~5 mins

Readonly class properties in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIt can only be assigned once, typically in the constructor.
BIt can be changed anytime after object creation.
CIt is the same as a private property.
DIt can only hold numbers.
Where can you assign a value to a readonly property?
AOnly outside the class.
BAnywhere in the class methods.
CInside the constructor.
DIn any function.
What error occurs if you try to change a readonly property after construction?
ARuntime error.
BCompile-time error.
CNo error, it changes normally.
DSyntax error.
Which keyword makes a class property immutable after initialization?
Areadonly
Bconst
Cprivate
Dstatic
Why might you choose readonly over private?
A<code>private</code> makes the property constant.
B<code>private</code> allows changes from outside.
C<code>readonly</code> hides the property completely.
D<code>readonly</code> allows read access but prevents changes.
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.