Home > Software design >  'Element implicitly has an 'any' type because expression of type 'string' c
'Element implicitly has an 'any' type because expression of type 'string' c

Time:01-10

I'm trying to display the following 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. 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.

But it still doesn't work, and I don't understand why.

CodePudding user response:

You can use keyvalue pipe to iterate on objects:

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

CodePudding user response:

To overcome the error you would need to specify type for 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']
    }
  •  Tags:  
  • Related