Home > OS >  How to declare type in typescript properly
How to declare type in typescript properly

Time:07-07

I am getting below the error in my code.

let getVal: string
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AppComponent'.
  No index signature with a parameter of type 'string' was found on type 'AppComponent'.ts(7053)

So, How to resolve like this type declaration issue in typescript.If anyone knows please help to resolve.

app.component.html:

<button *ngFor="let season of seasons" (click)="show(season)">
  {{ season }}
</button>

<div *ngIf="group1">Group 1 content</div>

<div *ngIf="group2">Group 2 content</div>

<div *ngIf="group3">Group 3 content</div>

app.component.ts:

  seasons = ['Group 1', 'Group 2', 'Group 3'];
  group1: boolean = false;
  group2: boolean = false;
  group3: boolean = false;

  show(val: string) { 
    for (var i = 0; i < this.seasons.length; i  ) {
      if (this.seasons[i] === val) {
        let getVal = val.toLowerCase().replace(/\s/g, ''); 
        this[getVal] = true; // getting error here
      } else {
        let getVal = this.seasons[i].toLowerCase().replace(/\s/g, ''); 
        this[getVal] = false; // getting error here
      }
    }
  }

CodePudding user response:

You could try to use (this as any)[getVal] = ....

However, I would recommend doing something like this:

app.component.ts

export class AppComponent {

    readonly groups: { [key: string]: boolean } = {};

    seasons = ['Group 1', 'Group 2', 'Group 3'];

    show(val: string) { 
        for (let i = 0; i < this.seasons.length; i  ) {
            if (this.seasons[i] === val) {
                const getVal = val.toLowerCase().replace(/\s/g, ''); 
                this.groups[getVal] = true;
            } else {
                const getVal = this.seasons[i].toLowerCase().replace(/\s/g, '');
                this.groups[getVal] = false;
            }
        }
    }
}

This isolates the "groups" from the rest of the component's class members and allows you to iterate, add, and remove elements without having to mess around with type casting, e.g.

Object.keys(this.groups).forEach(
    group => console.log(`${group}=${this.groups[group]}`);

app.component.html

<button *ngFor="let season of seasons" (click)="show(season)">
  {{ season }}
</button>

<div *ngIf="groups.group1">Group 1 content</div>

<div *ngIf="groups.group2">Group 2 content</div>

<div *ngIf="groups.group3">Group 3 content</div>

(or render groups dynamically)

<ng-container *ngFor="let entry of groups | keyvalue">
    <div *ngIf="!!entry.value">
        {{ group.key }} content
    </div>
</ng-container>
  • Related