【问题标题】:angular 2 type script error - TS2322角度 2 类型脚本错误 - TS2322
【发布时间】:2018-04-30 05:38:39
【问题描述】:

我正在开发 Angular 2 MEAN 应用程序项目。我的代码面临以下问题。

错误 TS2322: 类型 '{ 'id': string; “保龄球”:字符串; 'battingteam': 字符串; }' 不可分配给类型 'any[]'。
类型 '{ 'id': string; 中缺少属性 'includes' “保龄球”: 细绳; 'battingteam': 字符串; }'

我已将一个类变量声明为

startMatchInput : Array<any> = [{
       'id' : '',
       'bowlingteam' : '',
       'battingteam' : ''

  }];

我使用类中声明的函数放置的每个对象。基本上我正在使用 this.startMatchInput 变量中提到的键形成一个对象。

下面是函数中的代码。

function x(){
  var startMatchmasterObj = {
                'id' : '',
                'bowlingteam' : '',
                'battingteam' : ''

          };

startMatchmasterObj.id =  "943974937947";
               startMatchmasterObj.bowlingteam =  "098idsjvlnladfsj";
               startMatchmasterObj.battingteam =  "jzvlzc9a7dfs90as";

 this.startMatchInput = startMatchmasterObj; // here error is coming
}

我将函数中的局部变量分配给我的类变量,以便在需要时在外部访问它。但面临上述错误。

任何帮助或指示将不胜感激。我是 Angular 2 和 MEAN 堆栈开发的新手。

谢谢....

【问题讨论】:

  • startMatchInput 是一个数组,但 startMatchmasterObj 是一个对象。您可以将该对象添加到数组中 (this.startMatchInput.push(startMatchmasterObj))

标签: angular


【解决方案1】:

startMatchInput 的类型是any[]startMatchmasterObj 是对象而不是数组,因此它们的类型不兼容,因此出现错误。因此,您可以将 startMatchInput 的类型更改为any,也可以将startMatchmasterObj 包装在一个数组中进行分配。

startMatchInput: any = {    // declare it as any, rather than any[]
   'id' : '',
   'bowlingteam' : '',
   'battingteam' : ''
};    

// or...

this.startMatchInput = [startMatchMasterObj];    // wrap in an array

我猜,您的最佳选择将取决于您希望如何使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2017-04-10
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多