Javascript 在Angular 12中的接口定义的属性上迭代?
前角12用于工作:Javascript 在Angular 12中的接口定义的属性上迭代?,javascript,angular,typescript,Javascript,Angular,Typescript,前角12用于工作: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c => { this.content[c].forEach(topic => {
export interface Content {
categories: string[]
concepts: Topic[]
formulas: Topic[]
guides: Topic[]
}
//this.content is of type Content
['formulas', 'concepts'].forEach(c => {
this.content[c].forEach(topic => {
//....
});
})
但是现在它产生了错误(对于行this.content[c]
):
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“Content”。
在“Content”类型上找不到具有“string”类型参数的索引签名。ts(7053)
如何告诉Typescript this.content[c]是一组
主题实例?试着这样使用它:
['formulas', 'concepts'].forEach(c => {
this.content[c as keyof Content].forEach(topic => {
//....
});
})
我最终将设计更改为:
export interface ContentContainer {
categories: string[]
keyedTopics:Content
}
export interface Content {
[key: string]: Topic[]
}
这样,每个字符串
键总是映射到主题
数组。您的意思是不强制转换?