简体   繁体   English

TypeScript错误:保留字'this'用作名称

[英]TypeScript error: Reserved word 'this' used as name

I am trying to get this Node.js TypeScript definition to work, but WebStorm gives me a big list of errors with all the same message: 我试图让这个 Node.js TypeScript定义工作,但WebStorm给了我一个大错误列表,包含所有相同的消息:

Reserved word 'this' used as name. 保留字'this'用作名称。 This inspection reports on any uses of JavaScript reserved words being used as a name. 此检查报告使用JavaScript保留字作为名称的任何用法。 The JavaScript specification reserves a number of words which are currently not used as JavaScript keywords. JavaScript规范保留了许多当前未用作JavaScript关键字的单词。 Using those words as identifiers may result in broken code if later versions of JavaScript use them as keywords. 如果将更高版本的JavaScript用作关键字,则将这些单词用作标识符可能会导致代码损坏。

An example piece of code where this error happens due to the return type: 由于返回类型而发生此错误的示例代码:

错误示例

Why can't the this keyword be a type? 为什么this关键字不能成为类型? Am I perhaps using an old TypeScript compiler or is it a mistake in the typing? 我可能使用旧的TypeScript编译器,还是打字错误?


Edit: To get rid of the errors I've just replaced all these this types with the type of the containing class or interface. 编辑:为了摆脱我刚刚更换了所有这些错误的this类型的包含类或接口的类型。 For example, the errors in the given example are fixed by changing it to this: 例如,通过将其更改为以下内容来修复给定示例中的错误:

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

Although, this is not a solution to the actual problem. 虽然,这不是解决实际问题的方法。

Am I perhaps using an old TypeScript compiler ... ? 我可能使用旧的TypeScript编译器......?

Yes, upgrade to at least TS 1.7 to get polymorphic this support. 是的,升级到至少TS 1.7以获得这种支持的多态性

Seems you use old version of WebStorm. 似乎您使用旧版本的WebStorm。 WebStorm supports 'this' type starting from v11.0.3. WebStorm从v11.0.3开始支持'this'类型。

The following code compiles just fine in the typescript playground: 以下代码在typescript playground中编译得很好:

export interface E
{
    b(): this;
}

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

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

And according to link 'this' will be interpreted as 'any'. 根据链接 'this'将被解释为'any'。 So most likely there is something with webstorm. 所以最有可能的是webstorm。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM