Typescript - Tips & Tricks - Readonly Array

function sortAndReverse(list: number[]): number[] { return list.sort().reverse(); } const list =...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 11 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #10 Previous
    readonly modifier
  2. #11 Reading now
    Readonly Array
  3. #12 Up next
    Tuple
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
  11. #11 Readonly Array Current
  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
function sortAndReverse(list: number[]): number[] {
  return list.sort().reverse();
}

const list = [1, 4, 5, 2];
sortAndReverse(list);
console.log(list);

What’s the result of the final console log?

  1. [ 1, 4, 5, 2 ]
  2. [ 5, 4, 2, 1 ]
  3. [ 2, 5, 4, 1 ]

Unfortunately, the correct answer is the second one. Unfortunately

In this stupid example, you can see how some array methods can have some side effects. The sort and the reverse methods return a new array with the result but also they change the initial array. Typescript can help us to prevent these side effects using read-only arrays. The read-only arrays identify the methods that modify the initial array and raise an error when you call these methods. But now, how can you use the read-only array? It’s easy guys, you need to indicate the readonly modifier before the type of your array. So, the previous example can change in this way

function sortAndReverse(list: readonly number[]): number[] {
  return list.slice().sort().reverse();
}

const list = [1, 4, 5, 2];
sortAndReverse(list);
console.log(list);

In this case, the sortAndReverse method returns as result ”[ 5, 4, 2, 1 ]” like in the first example, but more important is that the final console log returns ”[ 1, 4, 5, 2 ]”, the initial value of the “list” array. If in this case, you try to remove the “slice” method, you can see how typescript indicates an error (Property ‘sort’ does not exist on type ‘readonly number[]’), and it helps you to prevent strange side effects.

It’s all for today! Bye Bye 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.