Aamir Rizwan
Aamir Rizwan

Reputation: 887

Typescript Error: Property 'items' does not exist on type 'MenuItem | MenuItem[]'

I'm trying to create a nested menu using PrimeNG. The below code is giving compilation error:

export class AppComponent {
    title = 'test-proj';
    items: MenuItem[];
    ngOnInit() {
        this.items = [
            {
                label: 'File',
                icon: 'pi pi-pw pi-file',

            },
            {
                label: 'Regions',
                icon: 'pi pi-fw pi-pencil',
                items: [] as MenuItem[]
            },
            {
                label: 'Help',
                icon: 'pi pi-fw pi-question',
            }
        ];

        for(let i = 0; i< 5; i++){
          this.items[1].items[i] = {
            label: 'R'+i,
            items: [] as MenuItem[]
          }
          console.log(this.items[1].items[i]);
          for(let j = 0; j< 4; j++){
            this.items[1].items[i].items[j] = {// error at this line
              label: 'A'+j, 
              items: [] as MenuItem[]
            }


          }
        }

    }
}

Error:

ERROR in app.component.ts(41,36): error TS2339: Property 'items' does not exist on type 'MenuItem | MenuItem[]'.
  Property 'items' does not exist on type 'MenuItem[]'.

package.json:

"dependencies": {
    "@angular/animations": "~7.0.0",
    "@angular/common": "~7.0.0",
    "@angular/compiler": "~7.0.0",
    "@angular/core": "~7.0.0",
    "@angular/forms": "~7.0.0",
    "@angular/http": "~7.0.0",
    "@angular/platform-browser": "~7.0.0",
    "@angular/platform-browser-dynamic": "~7.0.0",
    "@angular/router": "~7.0.0",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "primeicons": "^1.0.0",
    "primeng": "^7.0.0-beta.1",
    "rxjs": "~6.3.3",
    "zone.js": "~0.8.26"
}

One workaround is to use any as the type for items. I come from Java background and fail to understand why am I getting this error. Is there a way to fix this keeping the type of items as MenuItem?

Edit 1: logs

logs

Upvotes: 1

Views: 3191

Answers (1)

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

try this

 for(let i = 0; i< 5; i++){
    this.items[1].items[i] = {
       label: 'R'+i,
       items: [] as MenuItem[]
    }

    for(let j = 0; j< 4; j++){
       (this.items[1].items[i] as MenuItem).items[j] = {// error at this line
           label: 'A'+j, 
           items: [] as MenuItem[]
       }
    }
 }

Upvotes: 2

Related Questions