0
0
Typescriptprogramming~5 mins

Readonly properties in interfaces in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the readonly keyword do in a TypeScript interface?
It makes a property unchangeable after the object is created. You can read the value but cannot modify it.
Click to reveal answer
beginner
How do you declare a readonly property name of type string in an interface?
Use readonly name: string; inside the interface definition.
Click to reveal answer
beginner
Can you assign a new value to a readonly property after the object is created?
No, TypeScript will give an error if you try to change a readonly property after initialization.
Click to reveal answer
intermediate
Why use readonly properties in interfaces? Give a real-life example.
To protect important data from accidental changes. For example, a user ID should not change once set.
Click to reveal answer
beginner
Can readonly properties be set during object creation?
Yes, readonly properties can be set when the object is first created but not changed later.
Click to reveal answer
What happens if you try to change a readonly property in TypeScript?
ATypeScript shows an error.
BThe property changes without error.
CThe program crashes at runtime.
DThe property becomes undefined.
How do you mark a property as readonly in a TypeScript interface?
AUse the keyword <code>final</code> before the property name.
BUse the keyword <code>readonly</code> before the property name.
CUse the keyword <code>immutable</code> after the property name.
DUse the keyword <code>const</code> before the property name.
Can a readonly property be assigned a value when creating an object?
AYes, but only if the property is optional.
BNo, it must be set later.
CNo, it cannot be set at all.
DYes, it can be set during object creation.
Which of these is a good reason to use readonly properties?
ATo prevent accidental changes to important data.
BTo make properties private.
CTo allow properties to be changed anytime.
DTo improve runtime performance.
If an interface has a readonly property, can you omit it when creating an object?
AYes, readonly properties are always optional.
BNo, readonly means it must be included.
COnly if the property is optional.
DYes, readonly properties are ignored.
Explain what readonly properties in interfaces are and why they are useful.
Think about how you keep some information fixed, like a birthdate.
You got /4 concepts.
    Describe how to declare and use a readonly property in a TypeScript interface with a simple example.
    Show how to write the interface and create an object with that property.
    You got /3 concepts.