如何在类模型中声明一个类型?

时间:2016-10-04 02:16:14

标签: javascript angular typescript

我是angular2的新手。所以,请耐心等待。

到目前为止我尝试过:

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

再次:我尝试了数组和[]

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

这是没有子菜单声明的代码。

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' }
    ]
  }
]

这是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'.

任何帮助都对我意义重大。谢谢!

1 个答案:

答案 0 :(得分:0)

有一些事情你想要改变......首先,我建议使用interfacetype代替class因为你没有打电话new任何地方。

另一件事是,通过让submenu: array它不是可选的,因此预期在每个不是这种情况的实例上(树需要停在某处)。您可以使用?

来表示这一点

这将为您留下如下界面:

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

这将允许这项工作:

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

Example