简体   繁体   English

在TypeScript中键入`this`

[英]Typing `this` in TypeScript

Is there a way to set the type of this in TypeScript? 有没有一种方法来设置的类型, this在打字稿?

I'm sure there's plenty of uses for it, but in my particular case it's for typing a JS library, and writing a plugin for it. 我敢肯定它有很多用途,但是在我的特殊情况下,它是用于键入JS库并为其编写插件的。

For example: 例如:

// Some library
declare var SomeLib: sl.ISomeLibStatic;
declare module sl {
    interface ISomeLib extends ISomeLibApi {
        baseFn(): void;
    }

    interface ISomeLibStatic {
        new (): ISomeLib;
        API: ISomeLibApi;
    }

    interface ISomeLibApi {
    }
}

// Plugin file
declare module sl {
    // Extend the API signature declaration
    interface ISomeLibApi {
        extraFn(): void;
    }
}

module sl {
    // Implement the function
    SomeLib.API.extraFn = function () {
        // Get typing on this here
        this.baseFn();
    };
}

Anybody knows a way to do this without a variable like: var typedThis: ISomeLib = this; 任何人都知道在没有变量的情况下执行此操作的方法: var typedThis: ISomeLib = this; ?

Currently the only way I found was having cast it on every usage <ISomeLib>this which is cumbersome, and not defined in the type of the function. 目前,我发现的唯一方法是将它<ISomeLib>this每个用法<ISomeLib>this很麻烦,并且没有在函数的类型中定义。

There is no way to hint to the language service what context to apply to the function. 无法向语言服务提示要应用于该功能的上下文。

The only mechanism that will cleanly supply type checking and auto-completion without resulting in runtime artefacts is: 干净地提供类型检查和自动完成而不会导致运行时伪像的唯一机制是:

(<ISomeLib>this).baseFn();

Which compiles down to the desired: 编译成所需的代码:

this.baseFn();

It can be done as follows: 可以按照以下步骤完成:

function foo(this: MyType) { 
}

You can also use this: this to enforce the function to be called on the declaring context, or this: void to prevent the usage of this. 您还可以使用this: this来强制在声明上下文中调用该函数,或者this: void以防止使用this。

However, the target version for this feature is TypeScript 2.0 (although it is already implemented on the latest develop). 但是,此功能的目标版本是TypeScript 2.0(尽管已在最新开发的版本中实现)。

See here for details. 有关详细信息,请参见此处

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

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