Typescript - Tips & Tricks - readonly modifier

How many times we expect an object property to have a value but it isn't? In these cases,...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 10 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #9 Previous
    Index Signature
  2. #10 Reading now
    readonly modifier
  3. #11 Up next
    Readonly Array
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof
  4. #4 Union and Intersection
  5. #5 Overloaded Functions
  6. #6 this parameter
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier Current
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

How many times we expect an object property to have a value but it isn’t? Magic gif In these cases, unfortunately, we spend a lot of time searching for who changes the value of this property. Today I want to show you a special modifier that helps you to prevent this problem and preserve your time. This modifier is the readonly. The readonly modifier helps you to prevent someone can change your property, so, the object’s property can set only in the object initialization. A simple example

type Point = {
  x: number;
  y: number;
};
const point: Point = {
  x: 10,
  y: 10,
};
point.x = 20;
point.y = 20;

type ReadOnlyPoint = {
  readonly x: number;
  readonly y: number;
};
const readOnlyPoint: ReadOnlyPoint = {
  x: 10,
  y: 10,
};
readOnlyPoint.x = 20; // Cannot assign to 'x' because it is a read-only property
readOnlyPoint.y = 20; // Cannot assign to 'y' because it is a read-only property

In this example you can see how in the first case you can change the value of the properties ‘x’ and ‘y’; on the contrary, in the second case, you can’t change the properties because they are marked as readonly. As you can see, the readonly modifier can prevent the change of the values of the properties and save your code from annoying bugs. Typescript also exposes a special type to convert your types to full readonly types; this type is called ReadOnly. So we can review the previous example in this way

type Point = {
  x: number;
  y: number;
};
const point: Point = {
  x: 10,
  y: 10,
};
point.x = 10;
const readOnlyPoint: ReadOnly<Point> = {
  x: 10,
  y: 10,
};
readOnlyPoint.x = 10; // Cannot assign to 'x' because it is a read-only property
readOnlyPoint.y = 20; // Cannot assign to 'y' because it is a read-only property

From the readonly modifier, it’s all! Goodbye guys!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.