为什么不能使用此内部函数?

时间:2019-04-18 05:51:53

标签: typescript typescript-decorator

代码:

const f: any = function(...args: any[]) {
    const a = this;
};

错误:

semantic error TS2683 'this' implicitly has type 'any' because it does not have a type annotation.

1 个答案:

答案 0 :(得分:2)

您已启用noImplicitThis编译器选项,并且在新的f函数this中,表达式的类型隐式为any-因此出错。

要解决此问题,只需使用"fake" this parameter明确指定类型:

const f: any = function(this: typeof target, ...args: any[]) {
    // ...
};
  

默认情况下,函数内部的此类型为any。从TypeScript 2.0开始,您可以提供一个明确的this参数。这些参数是伪造的参数,首先出现在函数的参数列表中