TypeScript error: Reserved word 'this' used as name

TypeScript error: Reserved word 'this' used as name

我正在尝试使 this Node.js TypeScript 定义正常工作,但 WebStorm 给了我一大堆错误,其中包含所有相同的消息:

Reserved word 'this' used as name. This inspection reports on any uses of JavaScript reserved words being used as a name. The JavaScript specification reserves a number of words which are currently not used as JavaScript keywords. Using those words as identifiers may result in broken code if later versions of JavaScript use them as keywords.

由于 return 类型而发生此错误的代码示例:

为什么 this 关键字不能是类型?我可能使用的是旧的 TypeScript 编译器还是输入错误?


编辑: 为了消除错误,我刚刚将所有这些 this 类型替换为包含 class 或接口的类型。例如,给定示例中的错误通过将其更改为以下内容来修复:

export interface EventEmitter {
    addListener(event: string, listener: Function): EventEmitter;
    ...
}

虽然,这不是解决实际问题的方法。

以下代码在 typescript playground 中编译得很好:

export interface E
{
    b(): this;
}

class A implements E
{
    public b(): any
    {
        return 123;
    }   
}

let a = new A();
console.log(a.b());

而根据link,'this'会被解释为'any'。 所以很可能有 webstorm 的东西。

Am I perhaps using an old TypeScript compiler ... ?

是的,至少升级到 TS 1.7 以获得 polymorphic this 支持。

看来您使用的是旧版本的 WebStorm。 WebStorm 从 v11.0.3 开始支持 'this' 类型。