美好的一天。我是使用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);
}
}
任何帮助都将受到高度赞赏。
答案 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'},
]
}
];