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