如何正确声明输入字样
我要低于代码中的错误。
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
}
}
}
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
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用
(这是任何)[getVal] = ...
。但是,我建议这样做类似的事情:
app.component.ts
这将与其他组件的其他类成员隔离与类型铸造一起混乱,例如
app.component.html
(或动态渲染组)
You could try to use
(this as any)[getVal] = ...
.However, I would recommend doing something like this:
app.component.ts
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.
app.component.html
(or render groups dynamically)