[英]'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type in Object' in *ngFor
I'm trying to display the following object:我正在尝试显示以下 object:
export const articles = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}
Like this:像这样:
<h2>Browse through our articles:</h2>
<section *ngFor="let key of keys">
{{key}}
<div *ngIf="myArticles.hasOwnProperty(key)">
<span *ngFor="let arr of myArticles[key]"><app-list-detail [list]="arr"></app-list-detail></span>
</div>
</section>
Where arr gets sent to a child component as list . arr作为list发送到子组件的位置。 But I get the error in the title.
但我得到标题中的错误。 I thought it was because TS had no way to know if key was an actual property of myArticles , so I added the * ngIf above.
我认为是因为 TS 无法知道key是否是myArticles的实际属性,所以我在上面添加了 * ngIf 。
But it still doesn't work, and I don't understand why.但它仍然不起作用,我不明白为什么。
You can use keyvalue
pipe to iterate on objects:您可以使用键值
keyvalue
来迭代对象:
<h2>Browse through our articles:</h2>
<section *ngFor="let entry of articles | keyvalue">
{{entry.key}}
<span *ngFor="let arr of entry.value"><app-list-detail [list]="arr"></app-list-detail></span>
</section>
To overcome the error you would need to specify type for articles
.要克服该错误,您需要指定
articles
的类型。 You can specify type as:您可以将类型指定为:
export const articles: Record<string, string[]> = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.