簡體   English   中英

如何在打字稿中正確聲明類型

[英]How to declare type in typescript properly

我的代碼低於錯誤。

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)

那么,如何在打字稿中解決這種類型聲明問題。如果有人知道,請幫助解決。

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
      }
    }
  }

您可以嘗試使用(this as any)[getVal] = ...

但是,我建議這樣做:

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;
            }
        }
    }
}

這將“組”與組件的其他類成員隔離開來,並允許您迭代、添加和刪除元素,而不必搞亂類型轉換,例如

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>

(或動態渲染組)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM