Typescript - Tips & Tricks - Readonly Array

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

#typescript#webdev
Luca Del PuppoLuca Del Puppo
Article Series · Part 11 of 21TypeScript - Tips & Tricks
View full series (21)
  1. #10Previous
    readonly modifier
  2. #11Reading now
    Readonly Array
  3. #12Up next
    Tuple
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 modifier
  11. #11Readonly ArrayCurrent
  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
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.