【问题标题】:AngularX TS error Cannot invoke an expression whose type lacks a call signature [closed]AngularX TS错误无法调用类型缺少调用签名的表达式[关闭]
【发布时间】:2018-06-09 15:33:51
【问题描述】:

我正在创建这样的组件,但在 ng serve/building 时出现错误。 不要像一些评论者认为的那样与控制台上的错误混淆。 预期行为适用于构建和运行的代码。

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 有关。请解释。我不这么认为。

【问题讨论】:

  • 检查 ngOnInit() 中的 console.log(this.chartInput);
  • @orangespark nope.. 我会通过的。请比较它并标记重复。错误是一样的。但不同的用例。
  • @Ajay ...我想为此构建..你认为.??
  • 您在代码中使用的这个 sn-p 是否准确?

标签: javascript arrays angular typescript


【解决方案1】:

已知在使用联合类型 (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

【讨论】:

  • 谢谢。我实际上已经找到了修复 1 并解决了这个问题。但我真的很想检查它是否可以以其他方式工作。感谢修复 2 和微软关于此事的文档
猜你喜欢
  • 2019-12-15
  • 2019-07-24
  • 2017-02-03
  • 2019-09-10
  • 2018-12-25
  • 2023-03-20
  • 2019-09-07
  • 1970-01-01
相关资源
最近更新 更多