0
0
Typescriptprogramming~5 mins

Readonly properties in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the readonly keyword do in TypeScript?
It makes a property unchangeable after it is initialized. You can set it once, but cannot modify it later.
Click to reveal answer
beginner
How do you declare a readonly property in a TypeScript interface?
Use the readonly keyword before the property name, like readonly name: string;.
Click to reveal answer
intermediate
Can you assign a value to a readonly property inside a class constructor?
Yes, you can assign a readonly property inside the constructor, but not modify it outside.
Click to reveal answer
beginner
What happens if you try to modify a readonly property after initialization?
TypeScript will give a compile-time error saying you cannot assign to a readonly property.
Click to reveal answer
intermediate
Can readonly properties be used with arrays or objects to make them immutable?
Readonly properties prevent reassigning the property itself, but do not make the contents of arrays or objects immutable.
Click to reveal answer
What does the readonly keyword do in TypeScript?
APrevents modification of a property after initialization
BMakes a property optional
CAllows a property to be changed anytime
DDeletes a property from an object
Where can you assign a value to a readonly property in a class?
AOnly inside the constructor
BAnywhere in the class
COnly outside the class
DNowhere, it must be undefined
What error occurs if you try to change a readonly property after initialization?
ASyntax error
BRuntime error
CCompile-time error
DNo error, it changes normally
How do you declare a readonly property in an interface?
AUse <code>const</code> before the property name
BUse <code>readonly</code> before the property name
CUse <code>private</code> before the property name
DUse <code>static</code> before the property name
Does readonly make the contents of an array property immutable?
AYes, but only for string arrays
BYes, it makes the array contents immutable
CNo, it deletes the array contents
DNo, it only prevents reassigning the property itself
Explain how readonly properties work in TypeScript and where you can assign their values.
Think about when and where you can set a readonly property.
You got /4 concepts.
    Describe the difference between readonly properties and immutability of objects or arrays in TypeScript.
    Consider what readonly protects and what it does not.
    You got /4 concepts.