Iterating over the properties defined by an Interface in Angular 12?

Viewed 94

Pre Angular 12 this used to work:

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 => {
//....
      });
    })

However now it produces the error (For the line this.content[c]):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Content'. No index signature with a parameter of type 'string' was found on type 'Content'.ts(7053)

How do I tell Typescript that this.content[c] is an array of Topic instances?

2 Answers

try to use it like this:

['formulas', 'concepts'].forEach(c => {
    this.content[c as keyof Content].forEach(topic => {
        //....
    });
})

I ended up changing the design to this:

export interface ContentContainer {
    categories: string[]
    keyedTopics:Content
}

export interface Content {
    [key: string]: Topic[]
}

This way each string key always maps to a Topic array.

Related