What is preventing me from setting my Array to be read-only in TypeScript using this method?

In the provided documentation, it is explained how to achieve this using an interface. However, as I delve deeper into the language, I can't help but wonder why the following approach does not yield the same results?

type TraverseTuple<T extends Array<unknown>> = {
     readonly [P in keyof T]: T[P];
}

const test: TraverseTuple<[string, number, string, number]> = ['s', 1, 'o', 2];

test[1] = 0; // This assignment doesn't maintain readonly status !

Answer №1

There is a special read-only array type in JavaScript that restricts modifying the elements of the array unless it is reasserted to a regular array.

const example: ReadonlyArray<string|number> = ['s', 1, 'o', 2];

example[1] = 0;

However, when dealing with tuples, you must define an explicit type as shown below:

const example: Readonly<{ 0: string, 1: number, 2: string, 3: number }> = ['s', 1, 'o', 2];

example[1] = 1;

Answer №2

This feature is not officially supported. Tuples mapping functionality was only recently added in TypeScript 3.1 with this PR. According to the PR:

The use of readonly, -readonly, or +readonly annotations in a homomorphic mapped type currently does not affect array or tuple elements (there may be future considerations for mapping from Array to ReadonlyArray and vice versa, although this would not be entirely structure preserving as it may add or remove methods).

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

Unselecting a line will result in the disabling of all chart lines

Currently, I am working with Primeng and incorporating multiple charts into my view. One feature of Primeng that I have successfully implemented is disabling lines. I am following this particular example: Primeng provides a handy function on their site: ...

Utilize Polymer 3 component to import object values

In one of my polymer 3 components, I have declared an object property as follows: static get properties(): myInferface { return { myObject: { type: Object, notify: true, value: { showMe: false, text: ...

Simulate an HTTP request from a service class during a jasmine test

I initially believed that spying on services in Jasmine using the spyOn method and returning a value when the method is called was straightforward. However, it seems like my assumption may have been too simplistic? I intend to test the following action in ...

The attribute 'X' is not found in the type 'HTMLAttributes<HTMLDivElement>'.ts(2322)

Encountered an issue using JSX sample code in TSX, resulting in the following error: (property) use:sortable: true Type '{ children: any; "use:sortable": true; class: string; classList: { "opacity-25": boolean; "transition-tr ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

Refine a union type by considering the properties already defined in an object

interface CustomHTMLElement { htmlPropA: string, htmlPropB: string, } interface CustomHTMLInput { inputPropA: string, inputPropB: string, } type CustomElement = | CustomHTMLElement | CustomHTMLInput const element: CustomElement = { inputPr ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

Printing using *ngFor will display items in an ascending order

When attempting to display an object in markup, I am running into the issue of *ng printing it in ascending order instead of maintaining the original order. Ideally, I would like the elements to be printed as they are. You can view my code on StackBlitz ...

What are the best ways to work with LatLng objects?

When I run a request to retrieve data from a database, the response displayed in the console using JSON.Stringify() is as follows: sites : [{"siteName":"Site de Marseille", "siteAdress1":"rue du string", "siteAddress2":"string", "siteCodPost":"13010","sit ...

What is the reason for injecting a service into 2 modules following the Singleton Pattern?

Here is the current file situation: AppService AppModule AModule AComponent BModule BComponent Regarding the Service, I have noticed that Angular will create two separate instances of the service if it is injected into two compone ...

Elegantly intersect two types of functions in Typescript

Two function types are defined as follows: wrapPageElement?( args: WrapPageElementBrowserArgs<DataType, PageContext, LocationState>, options: PluginOptions ): React.ReactElement .. and .. wrapPageElement?( args: WrapPageElementNodeArgs<Data ...

Insert an ellipsis within the ngFor iteration

I'm currently working with a table in which the td elements are filled with data structured like this: <td style="width:15%"> <span *ngFor="let org of rowData.organization; last as isLast"> {{org?.name}} ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

The issue of not displaying the Favicon in Next.js is a common problem

I am currently using Next.js version 13.4.7 with the App directory and I am facing an issue with displaying the favicon. Even though the favicon image is located in the public folder and in jpg format, it is not being displayed on the webpage. However, w ...

Add an image to a MongoDB collection using Vue, TypeScript, Express, and Multer

I'm trying to upload an image to my database, but I'm not quite sure if I'm doing this correctly. Below is the code in my child component: <script setup lang="ts"> import { ref } from 'vue'; const movieTitle = ref ...

Trouble arises when attempting to modify a property inherited from a parent class in TypeScript while

I've defined a base class like the following: import Vue from "vue"; class ComponentBase extends Vue { constructor() { super(); this.left = 100; this.top = 100; this.isSelected = false; } public left: numb ...

Error message: Unable to retrieve parameter value from Angular2 ActivatedRoute

I am attempting to showcase the value of the activated route parameter on the screen, but I am facing difficulties. In the initial component, my code looks like this: <ul *ngFor="let cate of categories;"> <li (click)="onviewChecklists(cate.id) ...

When I apply filtering and grouping to the table, the rows in the mat table disappear

When using mat-table, grouping works fine without filtering. However, once the table is filtered or if the search bar is focused, ungrouping causes the rows in the table to disappear. I am looking for a solution that allows me to group and ungroup the tabl ...

What is the method for converting a string[] array to a record<string, boolean> format in typescript?

I have a string array that contains values I want to keep and use to create a new array called Record. For each value in the userValue array. For example: userValue: string[] = ["1111","2222","3333","4444"]; selectedOptions: Record<string, boole ...