AngularX TS错误无法调用其类型缺少调用签名的表达式

时间:2017-12-29 06:30:50

标签: javascript arrays angular typescript

我正在创建这样的组件,我在ng服务/构建时遇到错误。 一些评论者似乎认为,不要在控制台上混淆错误。 预期的行为是代码构建和运行。

TS error TS2349: Cannot invoke an expression whose type lacks a call signature

ngOnInit()

中的foreach函数中
  import { Component, OnInit, Input } from '@angular/core';
    import { ChartInput, MultiChartInput, ChartColorScheme } from "@shared/models/chart-input";

    @Component({
        selector: 'chart-legend',
        templateUrl: './chart-legend.component.html',
        styleUrls: ['./chart-legend.component.css']
    })
    export class ChartLegendComponent implements OnInit {

        @Input()
        public chartInput: ChartInput[] | MultiChartInput[];
        @Input()
        public legendColors: ChartColorScheme;

        public legends: Map<string, string> = new Map<string, string>();
        constructor() { }

        ngOnInit() {
            this.chartInput.forEach(
                (item, index) => {
                    this.legends.set(item.name, this.legendColors.domain[index]);
                });
            }
        }

export class ChartInput {
    name: string;
    value: number;

}
export class MultiChartInput {
    name: string;
    series: ChartInput[];
}
export class ChartColorScheme {
    domain: string[];
}

任何解决的帮助都表示赞赏。 如果有人认为这与此question有关。请解释。我不这么认为。

1 个答案:

答案 0 :(得分:4)

使用联合类型(Microsoft/TypeScript - Issue #7294)时会发生这种情况。正如issue comment

中所述
  

目前这是设计原因,因为我们在获取联合类型的成员时不会合成交叉调用签名 - 只有在联合类型上出现相同的调用签名。

在您的情况下,ChartInputMultiChartInput没有兼容的签名,因为它们都具有唯一的属性;即,ChartInputvalue: number,而MultiChartInputseries: ChartInput[]。您可以通过注释掉这些属性并看到错误消失(demo of experiment)来快速测试。

要在保持类型安全的同时解决错误,请将chartInput的类型更改为(ChartInput | MultiChartInput)[]

class ChartLegendComponent implements OnInit {
    public chartInput: (ChartInput | MultiChartInput)[];
    ...
}

demo of fix 1

...或演员this.chartInput

(this.chartInput as (ChartInput | MultiChartInput)[])
  .forEach(
      (item, index) => {
          this.legends.set(item.name, this.legendColors.domain[index]);
      });
  }

demo of fix 2

相关问题