Typescript - Tips & Tricks - Readonly Array

Full Stack Developer and JavaScript and TypeScript enthusiastic.
Search for a command to run...

Full Stack Developer and JavaScript and TypeScript enthusiastic.
No comments yet. Be the first to comment.
In this series, You'll see some tips and tricks using Typescript
Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same. This definition is picking from the typescript documentation. The tuple type is a powerful type that helps you to identify the ...
Today, I wanna show you how to set up your devices with Antigravity using only the agentic mode, without touching any code. At the last CodeMotion Rome, I got my special badge. A CM Node, a special ha

As a developer, you have to take control of your projects every day. Whether it is a company repository, an open source project you maintain or collaborate on, or a simple pet project. Gaining control over your projects often depends on the platform ...

My Antigravity first experience

Write clear and insightful commit messages using AI and GitLens.

We are in the AI era. New models emerge daily, and many applications have already integrated AI into their workflows. Gemini, OpenAI, Copilot, Deepseek, Llama, and many others enable AI in your applications or help you write code, but they all need a...

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?
Unfortunately, the correct answer is the second one.

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!