typescript TS 类型缺少以下属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54398775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:46:49  来源:igfitidea点击:

TS Type is missing the following properties

angulartypescriptcasting

提问by A.Service

I'm using Angular 7.x.x with TS in version 3.2.4.

我在 3.2.4 版中使用带有 TS 的 Angular 7.xx。

I have two TS interfaces. One ist extending the other one:

我有两个 TS 接口。一个是扩展另一个:

This is the main interface:

这是主界面:

export interface Result {
      var1: string;
      var2: number;
      var3: boolean;
} 

The second one just adds a property:

第二个只是添加了一个属性:

export interface ResultPlus extends Result {
      var4: boolean;
}

Now I have a service returning Observable<Result[]>.

现在我有一项服务返回 Observable<Result[]>.

In my component I subscribe on this service:

在我的组件中,我订阅了这项服务:

dataArray: ResultPlus[] = [];    

getResults(): void {
      this.service.getResults()
          .subscribe(data => {
            **this.dataArray** = (data as unknown as ResultPlus);
          });
     }

(There are no * in the code)

(代码中没有*)

Now the this.dataArray(bold above - **) is underlined in red and it says:

现在this.dataArray(上面的粗体 - **)用红色下划线表示:

error TS2740: Type 'ResultPlus' is missing the following properties from type 'ResultPlus[]': length, pop, push, concat, and 26 more.

错误 TS2740:“ResultPlus”类型缺少“ResultPlus[]”类型中的以下属性:length、pop、push、concat 等 26 个。

What am I doing wrong?

我究竟做错了什么?

Thank you in advance!

先感谢您!

回答by Jon Egerton

Try changing your cast to ResultPlus[](the array type) not the single instance:

尝试将您的演员表更改为ResultPlus[](数组类型)而不是单个实例:

**this.dataArray** = (data as unknown as ResultPlus[]);

ie, you've declared dataArray to be an array of ResultPlus type.

即,您已将 dataArray 声明为 ResultPlus 类型的数组。

If you're trying to add to this.dataArrayfor each item data, then you need to push to it - something like:

如果您尝试添加到this.dataArray每个 item data,那么您需要推送到它 - 例如:

this.dataArray.push(data as unknown as ResultPlus);