实施Angular 5接口时出现TS错误

时间:2018-08-10 01:47:14

标签: angular typescript

我有这个奇怪的错误,我不确定得到它的原因是什么。

所以我有这样声明的接口,

export interface ActivitySelection {
   header: string;
   activities: [
     {
       activityName: string;
       available: boolean;
     }
   ];
}

现在在我的组件之一中,我试图像这样使用界面。

let activity: ActivitySelection

activity = {
   header: 'TEST 1',
   activities: [
      {
         activityName: 'activity-1',
         available: true
      },
      {
         activityName: 'activity-2',
         available: false
      }
   ]
}

但是我收到TS错误,提示

[ts] Type '{ header: string; activities: [{ activityName: string; available: false; }, { activityName: strin...' is not assignable to type 'ActivitySelection'. Types of property 'activities' are incompatible. Type '[{ activityName: string; available: false; }, { activityName: string; available: true; }, { activ...' is not assignable to type '[{ activityName: string; available: boolean; }]'. Types of property 'length' are incompatible.

我不确定是什么问题,因为我正确使用了我的界面?

任何帮助将不胜感激!

谢谢

2 个答案:

答案 0 :(得分:1)

在界面中,您指定了win.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if(e.getKeyChar()==KeyEvent.VK_UP){ speedX=1; } } }); 将是一个数组,其中单个元素是您指定的对象。您需要将界面更新为以下内容:

activities

答案 1 :(得分:1)

即使以上答案提供了问题的答案,您也可以为活动创建接口,并将活动作为一种活动数组,

export interface ActivitySelection {
   header: string;
   activities: activity[];
}

export interface Activity{
  activityName: string,
  available: boolean
}