"元素隐式具有"any"类型,因为类型"字符串"的表达式不能用于索引 *ngFor 中的对象中的类型



我正在尝试显示以下对象:

export const articles = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}

像这样:

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

其中arr作为list发送到子组件。但我在标题中弄错了。我认为这是因为TS无法知道是否是myArticles的实际属性,所以我添加了上面的*ngIf

但它仍然不起作用,我不明白为什么。

您可以使用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>

要克服此错误,您需要为articles指定类型。您可以将类型指定为:

export const articles: Record<string, string[]> = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}

最新更新