我的代码中出现了以下错误。
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)
那么,如何解决 typescript 中的这种类型声明问题。如果有人知道请帮助解决。
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>
关于typescript - 如何正确声明 typescript 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72881664/