Angular 错误TS2345:类型为';菜单';不可分配给类型为的参数
你好。我不熟悉使用VSCode键入脚本 获取以下错误:Angular 错误TS2345:类型为';菜单';不可分配给类型为的参数,angular,typescript,Angular,Typescript,你好。我不熟悉使用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/cor
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);
}
}
代码:
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);
}
}
任何帮助都将不胜感激。只需指定
菜单项的类型,如下图所示,警告将消失
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'},
]
}
];
将MENUITEMS
的第一项设置为{state:'/',name:'HOME',type:'link',icon:'explore',badge:[],children:[]}
我已更改了代码,但仍会收到相同的错误。解决此问题的正确方法是为MENUITEMS
提供适当的类型,以帮助TypeScript编译器完成<代码>常量菜单项:菜单[]=[…]