Invoking a function on an immutable object

I have a code snippet that looks like this:

  private get headers(): Headers {
    const headers = new Headers();
    headers.set('Authorization', `Bearer ${this.auth.tokenSnapshot}`);
    return headers;
  }

The variable headers is defined as a constant. (This specific code is from Angular 4, so the Headers class can be found here).

My question is, in TypeScript, is it acceptable to invoke a mutating method on an instance variable that has been declared as constant?

In C++, this would not typically be allowed unless the mutator method itself was declared as constant. However, I am unsure if the same rule applies in TypeScript.

Answer №1

Using const to declare a variable does not guarantee immutability; it simply prevents reassignment.

It is acceptable to modify properties of a const object:

const data = {};
data.myVal = 'example';

However, attempting to reassign the entire object will result in an error:

const settings = {};
settings = 'new value';

Answer №2

Utilizing the const statement merely restricts the reassignment of a variable, but it does not inhibit mutations to objects and their properties. Therefore, rest assured that you are in the clear.

Answer №3

It's totally fine. When using typescript, the statement const varName = new Object(); indicates that you cannot assign a new value to the variable (varName = otherVarName), however, the object can still undergo mutations.

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

Accessing a property that doesn't exist on a union type in Phaser using TypeScript

Currently, I've been immersed in the world of game development with Phaser 3 by following this insightful tutorial at . However, my focus has now shifted towards deploying these games online and adapting the code for use with TypeScript while gearing ...

Support for dark mode in Svelte with Typescript and TailwindCSS is now available

I'm currently working on a Svelte3 project and I'm struggling to enable DarkMode support with TailwindCSS. According to the documentation, it should be working locally? The project is pretty standard at the moment, with Tailwind, Typescript, and ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

Issue with TypeScript: variable lacks an initializer and is not explicitly assigned within the constructor

Code: class Example { private server: string; constructor() { this.setServer(); } setServer(): void { this.server = 'server'; } } new Example(); Error: ⨯ Unable to compile TypeScript: src/index.ts:309:13 ...

Attempting to assign a value to the global or session object is not possible. This error occurs when trying to call an expression without a defined call

I established a new solution. import { Injectable } from '@angular/core'; @Injectable() export class SessionService implements ISession { private _session: string = "SomeValue"; constructor() { } set session(value) { this._session = ...

Modify the buttons in the Angular Material Nav-bar according to the current page

I've utilized Angular Material to design my navbar in the app.component.html page. Initially, it features a LOGIN button which should be hidden once the user successfully logs in. Current method: I'm currently disabling the login button based on ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

I'm curious about the significance of this in Angular. Can you clarify what type of data this is referring

Can anyone explain the meaning of this specific type declaration? type newtype = (state: EntityState<IEntities>) => IEntities[]; ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

After version 3.1, TypeScript no longer supports callback functions as argument types

I've encountered an issue with jQuery Terminal. My d.ts file is quite large, but it's not functioning correctly. I attempted to update dependencies, leading to everything breaking. Recently, I've been unable to update TypeScript due to error ...

Selecting a value in the cypress testing framework for an ion-select component in an

I am currently experiencing difficulties in writing Cypress tests for an Ionic Angular app that includes an ion-select and ion-select-options. Despite my efforts, I am unable to successfully click on the ion-select-options within the app using Cypress. I ...

Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

Could we apply 'ngZone: 'noop' specifically to a function or component in Angular?

I am currently utilizing a third-party library to create PowerPoint presentations in Angular (Version 5). The third-party library makes numerous asynchronous calls and promises, causing zone.js to keep track of more than 50 loops running simultaneously. Th ...

Checking the functionality of a feature with Jasmine framework in an Angular application

I am working on writing unit test cases and achieving code coverage for the code snippet below. Any advice on how to proceed? itemClick($event: any) { for (let obj of this.tocFiles) { let results = this.getchildren(obj, label); if (results) { conso ...

Using TypeScript, add an observable to an array of observables using RxJS

Can someone explain how to include Observable<News> in an array of observables? newsArray: Observable<Array<any>>; addNews(newsId: number) { let news = this.newsService.getNewNews(newsId); // this results in an Observable<News> ...

Discovering the length of a video in Angular 4.3.1 with ng2-file-upload: A step-by-step guide

I am currently utilizing ng2-file-upload to upload videos with a maximum duration of 15 minutes. I am looking for a way to retrieve the duration of the video just before uploading it to the server. The allowed file extensions are: .MOV, .MPEG4, .AVI, .FL ...

Differences between Arrays of Numbers and Objects in Typegoose

Exploring Typegoose and encountering a puzzling issue. I defined a class with a field meant to store an array of numbers like this: class A { ... some other properties ... @prop({ required: true }) public nums!: number[]; } Here's a snippet of ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...