3
votes

Good day. I'm new to Type Script, using VSCode.

Getting following errors:

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

the code:

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

Any help will be highly appreciated.

1
set first item of MENUITEMS to { state: '/', name: 'HOME', type: 'link', icon: 'explore', badge: [], children: [] }Hasan Fathi
I have changed the code but still get the same error.Herry Wijaya
The correct way to fix this is to give your MENUITEMS an appropriate type to help the TypeScript compiler out. const MENUITEMS: Menu[] = [...]Daniel W Strimpel

1 Answers

8
votes

Just specify the type of MENUITEMS like below, the warning will go away

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