错误TS2345:类型“菜单”的参数不能分配给类型的参数

时间:2018-05-09 03:28:06

标签: angular typescript

美好的一天。我是使用VSCode的Type Script的新手。

获取以下错误

error TS2345: Argument of type 'Menu' is not assignable to parameter of type '{ state: string; name: string; type: string; icon: string;
 badge?: undefined; children?: undefine...'

代码

import { Injectable } from '@angular/core';

export interface BadgeItem {
  type: string;
  value: string;
}

export interface ChildrenItems {
  state: string;
  name: string;
  type?: string;
}

export interface Menu {
  state: string;
  name: string;
  type: string;
  icon: string;
  badge?: BadgeItem[];
  children?: ChildrenItems[];
}

const MENUITEMS = [
  {
    state: '/',
    name: 'HOME',
    type: 'link',
    icon: 'explore'
  },
  {
    state: 'account',
    name: 'ACCOUNT',
    type: 'sub',
    icon: 'explore',
    badge: [
      {type: 'purple', value: 'new'}
    ],
    children: [
        {state: 'users', name: 'USERS'},
    ]
  }
];

@Injectable()
export class MenuService {
  getAll(): Menu[] {
    return MENUITEMS;
  }

  add(menu: Menu) {
    MENUITEMS.push(menu);
  }
}

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:7)

只需指定MENUITEMS的类型,如下所示,警告就会消失

const MENUITEMS : Menu[] = [
  {
    state: '/',
    name: 'HOME',
    type: 'link',
    icon: 'explore'
  },
  {
    state: 'account',
    name: 'ACCOUNT',
    type: 'sub',
    icon: 'explore',
    badge: [
      {type: 'purple', value: 'new'}
    ],
    children: [
        {state: 'users', name: 'USERS'},
    ]
  }
];