Typescript is the only way.

How to get read-only arrays in TypeScript? Declaring a variable as a const is not enough, it prevents reassignment of its value but can still be modified. With JavaScript, you’re out of luck. TypeScript comes to the rescue with its Readonly type. Let’s see how it works.

Welcome to Panaxeo Tech Tips. Our monthly section with tips from our Club-Frontend members and more!

Defining a read-only array

To make an array read-only, simply add the assertion as const.


const cities = ['Paris', 'London', 'New York'] as const;

If you hover over the cities variable to see its type, you’ll get readonly ["Paris", "London", "New York"]. TypeScript explicitly states the elements in their order which makes it a read-only tuple.

Now, if you try to modify it by pushing a new element, you get a type error Property 'push' does not exist on type 'readonly ["Paris", "London", "New York"]'.


cities.push('Beijing'); // Type Error
cities.pop(); // Type Error
cities[0] = 'Roma'; // Type Error
 

Prevent calling self-modifying array methods

The Readonly type is especially useful when you’re using array methods and are not sure if a particular method modifies the array or not. Array methods like sort, reverse and splice modify the original array while map, filter, reduce and slice don’t.

You probably already know all this, but your junior colleague may not. So it’s good to be explicit about whether modifications are allowed or not.

To test this out, let’s create a function that takes a readonly array as a parameter, sorts it and prints it out to the console.



function printSorted(arr: Readonly<string[]>) {
  arr.sort(); // Type Error
  console.log(arr);
}

TypeScript won’t allow you to call sort on a read-only array and shows a type error. To make this right, you’ll need to create a copy first and then modify it.


function printSorted(arr: Readonly<string[]>) {
  const sorted = [...arr].sort();
  console.log(sorted);
}

TypeScript knows that you are not modifying the original array anymore and the error is gone.

Feel free to use this TypeScript Playground link to play around with read-only types.

And that’s all folks!





Found this little tip useful?
Maybe you’ve got some questions of your own, or maybe there’s a tip you’d like to share.
Let us know, our #club-frontend would love to hear it!

Mario Cerven

Software Engineer @ Panaxeo.

JavaScript enthusiast and founder of Panaxeo Frontend Club.

Previous
Previous

A child and a half and counting

Next
Next

Get a job + With us!