Encountering TS7053 error while trying to access component variables using type indexing in Angular 13

When trying to access a variable with type indexing in Angular 13, I encountered a TS7053 error. However, in this Stackblitz example, the same code works without any errors.

export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  Prop01 : boolean = false;
  Prop02 : boolean = false;
  Prop03 : boolean = false;

  private setProp(prop: string, value: boolean): void {

    this[prop] = value;   // this works in the Stackblitz but not in my project

  }
}

The only difference is that I'm using version 13 while Stackblitz still uses version 12. I checked my VS Code extensions and noticed that Ts Lint was deprecated in favor of Es Lint. I disabled it and restarted VS Code, but this[prop] still triggers an error that states:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyComponent'. No index signature with a parameter of type 'string' was found on type 'MyComponent'.

I have successfully done this in older Angular versions, so I'm puzzled by why it is not working suddenly. Does anyone have an insight into why this is happening?

Answer №1

To improve your code, I recommend defining an enum containing those variable names:

export enum PropertyEnums {
  Prop01: 'Prop01',
  Prop02: 'Prop02',
  Prop03: 'Prop03'
}

Component:

import { PropertyEnums } from './propertyEnums.ts'

export class AppContainer  {
  name = 'Vue';
  Prop01 : boolean = false;
  Prop02 : boolean = false;
  Prop03 : boolean = false;

  private setProperty(prop: string, value: boolean): void {
    this[prop as PropertyEnums] = value;
    console.log(this[prop as PropertyEnums]); // true or false, depending on the value set
  }
}

Starting from Angular version 12, strict mode is enabled by default, ensuring stronger typing. It is advisable to define a signature for accessing parameters in order to comply with this strict mode. In earlier versions, strict mode had to be manually enabled.

Answer №2

When working with three separate variables instead of an object, like in your scenario, it is recommended to use a type declaration for your variable names. By defining a type for your variables, you can then use the as keyword to specify the type when setting the variables. Here's an example:

type PropType = 'Prop01' | 'Prop02' | 'Prop03';

private setProp(prop: string, value: boolean): void {
  this[prop as PropType] = value;
}

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

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .p ...

Is it necessary to continue utilizing PropTypes when incorporating Typescript into a React application?

Typescript brings significant advantages in terms of type validation. Does it completely replace the necessity of using PropTypes? Or do PropTypes still offer unique benefits? ...

Difficulty with Angular 11 Material Theme showing Purple/Green color combination

After integrating Angular Material into my project using Angular-CLI, I opted for the Purple/Green pre-built theme. Despite the preview showing a dark background color for the theme, my background remains white. I'm puzzled as to why the color hasn&ap ...

Encountering a memory issue while trying to read and display Excel data in an Angular 2 application

Currently, I am working on an asp.net web API that utilizes OpenXML SDK for Excel to read data from an Excel file and display it in an Angular2 application. The dataset consists of approximately 70,000 rows that need to be displayed all at once without any ...

Type Conversion in Typescript

After receiving JSON data that can be in the form of a TextField object or a DateField object, both of which inherit from the Field superclass, I am faced with the task of converting this JSON into a Field object. To further complicate matters, I need to ...

Is there a way to verify that my transition from angular 2 to angular 4 in my app was successful?

Previously, my .NET WebAPI application utilized angular 2, but I made the decision to transition to angular 4. To upgrade, I executed the following commands in the cmd within my project directory (in addition to addressing any missing dependencies): npm ...

Angular 2: Finding the object with the highest attribute value in an array of objects

I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript? i ...

Creating a feature that automatically determines the data type of a value using the provided key

My object type has keys that map to different types: type Value = { str: string; num: number; }; I am working on creating a universal format function: const format = <K extends keyof Value>(key: K, value: Value[K]): string => { if (key === ...

Insert a new item into an Observable within Ionic 4

My lecturer has been guiding me as a beginner in Ionic development. Currently, I am working on an Ionic 4 shopping application where users can add items to their wishlist. The item IDs are stored in the wishlist collection in Firebase Firestore. However, I ...

Executing the cucumberjs + playwright tests after starting the angular app using the ng serve command

Our testing process involves using cucumberjs and playwright. Is it possible to initiate Angular with ng serve (using test configuration) before running our tests, and then close the application once the tests are complete? Similar to configuring a web s ...

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

Error: 'directive' element is unrecognized in the test environment

In order to convert this structure into an npm module, the following files and directories need to be included: . ./angular.json ./karma.conf.js ./package.json ./tsconfig.json ./demo ./demo/index.html ./demo/main.ts ./demo/test.ts ./demo/tsconfig.app.json ...

Variables for Angular Material themes

My app has multiple theme files, and I select the theme during runtime. .client1-theme{ // @include angular-material-theme($client1-theme); @include all-component-colors($client1-theme); @include theme-color-grabber($client1-theme, $client1-a ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular <tr *ngFor="let computer in _Computers; let i = index;"> <td>{{computer.Name}}</td><td>{{computer.Optional}}</td> <td> <input matInput [formControl] = " ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Implementing a unit test in Angular for an HTTP interceptor that adds an XCSRF token to the header

My current task involves unit testing a global HTTP interceptor that retrieves the XCSRF token from a service call getResponse() and appends it to the header only in POST requests using the postResponse() method (as described below). I have attempted to t ...

Implementing the click event in angular2-openlayers will display the information for the selected marker

Exploring Angular and Openlayers (3) is a new endeavor for me. Recently, I stumbled upon this open source library that conveniently wraps Openlayers within Angular. A straightforward question has come to mind: How can I detect when a user clicks on a gene ...

Recommendations for Organizing Multiple "Isolated" Applications Using MVC 5 and Angular 2

We are currently managing a large MVC 5 ASP.NET 4.5.1 web application that follows the concept of treating each page as its own application due to the vast areas it covers. The existing pages are built using JQuery, regular Javascript, and Handlebars templ ...

Tips for bringing in an enum from TypeScript?

I am working with a module defined in TypeScript that looks like this: declare module MyTypes { export enum MyEnum { GOOD = 'Good', BAD = 'Bad', UNKNOWN = '-' } export interface MyType1 { ...