What distinguishes ReadonlyArray from the declaration "readonly arr: T[]"?

Check out this unique playground.

interface Feature {
  readonly name: string;
}

// <Test>
// This is OK
interface Foo1 {
  readonly arr: ReadonlyArray<Feature>;
}
function save1(foo: Foo1) {
  console.log(foo);
}
// </Test>


// <Test>
// bad? why?
interface Foo2 {
  arr: ReadonlyArray<Feature>;
}
function save2(foo: Foo2) {
  console.log(foo);
}
// </Test>

// <Test>
// bad? why?
interface Foo3 {
  readonly arr: Feature[];
}
function save3(foo: Foo3) {
  console.log(foo);
}
// </Test>

I believed that Foo1, Foo2, and Foo3 were identical, but according to

@typescript-eslint/prefer-readonly-parameter-types
, they are not. In essence,

  • Foo1 consists of both readonly and ReadonlyArray
  • Foo2 only contains ReadonlyArray
  • Foo3 solely has readonly

What sets these interfaces apart?

Answer №1

When using the function save2, I have the freedom to perform the following:

foo.arr = [];

However, when working with save3, I am allowed to execute the following code:

foo.arr.push({name: 'bar'});

It's important to note that none of these actions are permitted in save1.

Answer №2

When it comes to ImmutableArrays, they are essentially non-changeable. Therefore, any attempts to modify the elements within this array will be unsuccessful.

In contrast, when using readonly arr: Feature[], the variable arr cannot be reassigned, but it is possible to alter the contents of the array itself.

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

Is it advisable to use an if statement or question mark in TypeScript to prevent the possibility of a null value?

Currently delving into TypeScript and exploring new concepts. I encountered a scenario where inputRef.current could potentially be null, so I opted to directly use a question mark which seems to work fine. However, in the tutorial video I watched, they use ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Navigate back to the initial page in Ionic2 using the navpop function

I have an application that needs to guide the user step by step. While I am aware of using navpop and navpush for navigating between pages, I am unsure about how to use navpop to go back to the first page. Currently, I am attempting to pop() twice if ther ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Initial state was not properly set for the reducer in TypeScript

Encountered an error while setting up the reuder: /Users/Lxinyang/Desktop/angular/breakdown/ui/app/src/reducers/filters.spec.ts (12,9): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ selectionState: { source: ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

What is the most secure method to define options and retrieve their values in a type-safe manner?

I am currently utilizing a library that offers an interface with a great deal of flexibility. type Option = number | { x?: number; y?: number; z?: number; } interface Options { a?: Option; b?: Option; c?: Option; d?: Option; } function init ...

Error: The function to create deep copies of objects is not working properly due to TypeError: Object(...) is not a

Encountering a TypeError: Object(...) is not a function in the following situation: To set up the state of a component with a specific Article (to be fetched from the backend in componentDidMount), I am implementing this approach // ArticlePage.tsx import ...

Is there a way to integrate TypeScript with styled components to display suggested properties on the component?

Hey there fellow developers! I'm currently diving into the world of TypeScript and trying to get the hang of it. One thing that's bothering me is not being able to see recommended props on a styled component while using TypeScript. For instance ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

TypeScript utility function that retrieves properties from an interface based on a specified type

Is there a way to create a new object type that includes only properties from another Object that match specific types, as opposed to property names? For example: interface A { a: string; b: number; c: string[]; d: { [key: string]: never }; } int ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

I am struggling to comprehend the concept of dependency injection. Is there anyone available to provide a clear explanation for me?

I am working on a NestJS application and trying to integrate a task scheduler. One of the tasks involves updating data in the database using a UserService as shown below: import { Injectable, Inject, UnprocessableEntityException, HttpStatus, } fro ...

Typescript: Select just one option from the union

There is a specific Query type that contains the getBankAccounts property: export type Query = { getBankAccounts: GetBankAccountsResponseOrUserInputRequest, }; This property can return either a GetAccountsResponse or a UserInputRequest: export type Ge ...