What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement:

TypeScript includes a special type called ReadonlyArray, which is essentially an Array without any methods for mutation. This ensures that you cannot modify your arrays once they have been created:

To verify this concept, I decided to experiment with the sample code below:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!

Upon compiling the aforementioned code snippet into JavaScript, I observed the resulting transformation:

var a = [1, 2, 3, 4];
var ro = a;
ro[0] = 12; // works
ro.push(5); // works
ro.length = 100; // works
a = ro; // works

The compiled JavaScript code indicates that the variable ro is now mutable within the JavaScript environment, allowing other JavaScript functions to alter its contents. This led me to ponder why TypeScript did not create a derivative subclass of the Array object specifically tailored for ro, with the mutable methods removed. Is there something crucial that I am overlooking here?

Answer №1

Unlike some other programming languages, TypeScript does not aim to interfere with runtime operations. Early discussions considered:

  • Enforcing types during runtime
  • Making private variables truly private at runtime

More nuanced questions were likely brought up as well.

The conclusion was that TypeScript was designed not to replace JavaScript but rather to enhance it through design and compilation processes, ultimately generating idiomatic JavaScript code.

As a result, there may be instances where TypeScript rules are breached in external code, such as with access modifiers and read-only arrays - however, this divergence from TypeScript's standards is not the project's intent.

Answer №2

Interfaces and types, such as private and public access modifiers, are concepts in Typescript that do not persist after compilation: During coding, the compiler/IDE will alert you to any mistakes, but once your code is converted to pure Javascript, there is nothing stopping you from assigning a string to a variable declared as a number or accessing a private member.

For instance, consider this example from an online demo:

https://i.sstatic.net/2qxMe.png

In the Typescript code on the left, there are two errors:

  • The attribute is designated as private
  • The attribute is not of type number

However, once transpiled, this code would be considered valid (if you click on Run, it runs without issues).

Types and interfaces serve mainly to catch potential errors during development, but they are not present in runtime.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...

Unable to dismiss message in Django

I'm a beginner in Django and I recently followed a tutorial to add message alerts to my code. The alerts are displaying correctly, but unfortunately, I am having trouble closing them using the 'x' button. https://i.stack.imgur.com/BQS1S.png ...

Node.js - Hitting maximum call stack size limit despite using process.nextTick()

I am currently developing a module for creating "chainable" validation in Express.js: const validatePost = (req, res, next) => { validator.validate(req.body) .expect('name.first') .present('This parameter is required') ...

Mongodb/mongoose encountering issues with saving data only once, resulting in a 500 error

When I send json to my node.js/express app, it successfully receives the data and performs the desired action, but only once. After starting the appjs for the first time, it returns a 200 response code and saves the data to my mongodb. However, any subsequ ...

The Javascript Image() function fails to load or render

I am currently in the process of developing a basic Sprite class for implementation in a canvas game. However, I am encountering an issue where the image specified during the creation of a new instance of the class does not trigger the onload or onerror ev ...

After activating the rewrite feature on Tomcat valve, JavaScript is loading twice

I've implemented the Tomcat rewrite valve in my single-page application to direct all requests, except for static resources, to my index.html file. Here is what my rewrite.config looks like: RewriteCond %{REQUEST_URI} (?!.*\.(?:jpg|png|css|js|js ...

what is the best way to eliminate comments from nested arrays when using useReducer?

Can someone help me figure out how to use useReducer and useContext to manipulate global state? I specifically need to know how to delete comments using useReducer. Data Structures View the interface image here Sample Data Array export const listsData:IDa ...

How to turn off automatic password suggestions in Chrome and Firefox

Currently, I have integrated a 'change password' feature which includes fields for 'old password', 'new password', and 'retype password'. However, the autocomplete feature is suggesting passwords from other user acco ...

How to Use AJAX to Read a Text File in JavaScript

Having trouble with AJAX! I have successfully set up a marquee on my website, but now I want it to dynamically fetch the text from a text file. The goal is to read the text from the file (which contains only one line) and assign it to a global variable nam ...

Waiting for Node/Express to process request

I'm fairly new to the world of Node.js and so far, it's been amazing. However, I've run into a minor issue while running node (with express) locally - Once I reach the 10th request, each subsequent one hangs and shows as Pending in the Chrom ...

Use Python to fetch a file from a webpage without having to actually open the webpage

I needed a method to automate the download of a file from a particular website without having to manually open the website. Everything should be done in the background. The website in question is Morningstar, and a specific example link is: . On this page ...

Ensuring data types for an array or rest parameter with multiple function arguments at once

I am looking for a way to store various functions that each take a single parameter, along with the argument for that parameter. So far, I have managed to implement type checking for one type of function at a time. However, I am seeking a solution that al ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

Discovering a website's console content using the "web-request" npm package

I recently added the web-request NPM package to my project with the goal of retrieving console messages from a specific website. However, I encountered an issue as I was unsure of how to achieve this. var result = await WebRequest.get('http://disco ...

Looking for a dynamic solution to retrieve over 100 data products in Angular JS? Let's explore methods to efficiently call a large volume of

Just starting out with Angular JS and working on creating a searchable product list gallery using Angular JS. Currently, all my product data is in the same js file which I know isn't the best solution. I would like to make it dynamic by connecting to ...

Utilize .GLB and Blender file formats within a Gridsome project developed with Vue.js

I am working on a project using Three.js in Gridsome, but I am facing difficulties importing .glb files (3D models) with GLTFLoader. While Gridsome recognizes img (png/jpg) or .js files stored in src/assets, it does not seem to support glb files. This is ...