【问题标题】:error TS2345: Argument of type 'Menu' is not assignable to parameter of type错误 TS2345:“菜单”类型的参数不可分配给类型参数
【发布时间】:2018-10-19 01:59:27
【问题描述】:

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

得到以下错误

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);
  }
}

我们将不胜感激。

【问题讨论】:

  • MENUITEMS的第一项设置为{ state: '/', name: 'HOME', type: 'link', icon: 'explore', badge: [], children: [] }
  • 我更改了代码,但仍然出现同样的错误。
  • 解决这个问题的正确方法是给你的 MENUITEMS 一个合适的类型来帮助 TypeScript 编译器。 const MENUITEMS: Menu[] = [...]

标签: angular typescript


【解决方案1】:

只需像下面这样指定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'},
    ]
  }
];

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2017-02-07
    • 2018-02-09
    • 2022-11-21
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多