user111111 user111111 - 2 months ago 17
TypeScript Question

How to declare submenu inside class model?

I am new to angular2. So, please bear with me.

What I have tried so far:

export class Navbar {
name: string;
submenu: {
name: string;
}
}


Again: I tried array and []

export class Navbar {
name: string;
submenu: array;
}


This is the code without submenu declaration.

export class Navbar {
name: string;
}

const NAVBAR: Navbar[] = [
{ name: 'Company Data' },
{ name: 'Client Data',
submenu: [
{ name: 'Balance' },
{ name: 'Settlement' }
]
},
{ name: 'Bookie Data' },
{ name: 'Bank Data' },
{ name: 'Journal Entry' },
{ name: 'Journal Bank' },
{ name: 'Report',
submenu: [
{ name: 'General Ledger' },
{ name: 'Trial Balance' },
{ name: 'Profit/Loss' },
{ name: 'Balance Sheet' }
]
},
{ name: 'Control' },
{ name: 'Input',
submenu: [
{ name: 'Company' },
{ name: 'Client' },
{ name: 'Bookie' },
{ name: 'Master' },
{ name: 'Client Agent' },
{ name: 'Bookie Balance' },
{ name: 'Import Client Data' },
{ name: 'Chart Of Account' },
{ name: 'Bank' },
{ name: 'Bank Company' }
]
}
]


This is the error thrown by angular.

app/app.component.ts(10,5): error TS2322: Type '({ name: string; } | { name: string; submenu: { name: string; }[]; })[]' is not assignable to type 'Navbar[]'.
Type '{ name: string; } | { name: string; submenu: { name: string; }[]; }' is not assignable to type 'Navbar'.
Type '{ name: string; submenu: { name: string; }[]; }' is not assignable to type 'Navbar'.
Object literal may only specify known properties, and 'submenu' does not exist in type 'Navbar'.


Any help would mean so much to me. Thanks!

Answer

There a couple of things you will want to alter... First of all, I would suggest using an interface or type instead of a class because you're not calling new anywhere.

The other thing, is that by having submenu: array it is not optional and is therefore expected on every instance which will not be the case (the tree needs to stop somewhere). You can denote this by using a ?

That will leave you with an interface like this:

export interface Navbar {
  name: string;
  submenus?: Navbar[];
}

Which will allow this to work:

const navbars: Navbar[] = [
  { name: 'Company Data' },
  { name: 'Client Data', 
    submenus: [
      { name: 'Balance' },
      { name: 'Settlement' }
    ]
  }
];

Example

Comments