0
0
Typescriptprogramming~5 mins

Readonly utility type in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the Readonly utility type do in TypeScript?
It makes all properties of an object type read-only, so they cannot be changed after initialization.
Click to reveal answer
beginner
How do you apply the Readonly utility type to an interface Person?
You write Readonly<Person> to create a new type where all properties of Person are read-only.
Click to reveal answer
beginner
Can you modify properties of an object typed with Readonly after it is created?
No, properties are read-only and TypeScript will give an error if you try to assign new values.
Click to reveal answer
intermediate
Example: What is the error in this code?<br><pre>type User = { name: string };
const user: Readonly&lt;User&gt; = { name: 'Alice' };
user.name = 'Bob';</pre>
Error: Cannot assign to 'name' because it is a read-only property.
Click to reveal answer
beginner
Why use Readonly utility type in your code?
To prevent accidental changes to objects, making code safer and easier to understand by enforcing immutability.
Click to reveal answer
What does the Readonly utility type do?
AConverts properties to optional
BMakes all properties of an object read-only
CAllows properties to be changed anytime
DRemoves all properties from an object
How do you declare a read-only version of a type Car?
AReadonly<Car>
BMutable<Car>
CPartial<Car>
DRequired<Car>
What happens if you try to assign a new value to a read-only property?
AThe value changes successfully
BThe property becomes optional
CThe property is deleted
DTypeScript shows an error
Which of these is a benefit of using Readonly?
APrevents accidental data changes
BMakes code run faster
CAllows dynamic property addition
DRemoves type checking
Can Readonly be used on nested objects automatically?
AIt removes nested objects
BYes, it applies deeply by default
CNo, it only applies to the first level properties
DIt converts nested objects to arrays
Explain what the Readonly utility type does and why it is useful.
Think about how it stops you from changing object properties after creation.
You got /4 concepts.
    Describe how you would use Readonly with a TypeScript interface and what happens if you try to modify a property.
    Consider the syntax and the error you get when changing a read-only property.
    You got /4 concepts.