【问题标题】:Function variable assigned to a Class using Typescript使用 Typescript 分配给类的函数变量
【发布时间】:2018-03-04 16:34:44
【问题描述】:

假设你有一个这样的 Typescript class

 class CompExt extends Comp {
        public static sum(a: number, b: number): number {return a+b};
    };

函数 sum 将与原始类略有不同,它必须是静态的。

你的实际代码是

let ff: Function = CompExt;
console.log('the summ works fine',ff.sum(1,2));

代码编辑器和编译器都会警告我:

bas.ts(47,16): error TS2339: Property 'sum' does not exist on type 'Function'. 

有没有办法避免编译错误?如果我使用 any 而不是 Function 一切都很好,但我想知道 Typescript 是否支持这种风格。

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    可以使用装饰器为您的情况提供可能的解决方案。检查这个答案Static property on a class

    【讨论】:

      【解决方案2】:

      只是不要将类型指定为Function,因为它不是泛型函数,而是CompExt

      如果真的要指定类型,可以使用:let ff: typeof CompExt = CompExt

      【讨论】:

      • 这是完美的。因此,即使我使用 ff,我也可以让我的编辑器自动完成和更正,如果我使用任何或不输入,这将不会发生。谢谢。
      猜你喜欢
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多