繁体   English   中英

在TypeScript中键入`this`

[英]Typing `this` in TypeScript

有没有一种方法来设置的类型, this在打字稿?

我敢肯定它有很多用途,但是在我的特殊情况下,它是用于键入JS库并为其编写插件的。

例如:

// 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();
    };
}

任何人都知道在没有变量的情况下执行此操作的方法: var typedThis: ISomeLib = this;

目前,我发现的唯一方法是将它<ISomeLib>this每个用法<ISomeLib>this很麻烦,并且没有在函数的类型中定义。

无法向语言服务提示要应用于该功能的上下文。

干净地提供类型检查和自动完成而不会导致运行时伪像的唯一机制是:

(<ISomeLib>this).baseFn();

编译成所需的代码:

this.baseFn();

可以按照以下步骤完成:

function foo(this: MyType) { 
}

您还可以使用this: this来强制在声明上下文中调用该函数,或者this: void以防止使用this。

但是,此功能的目标版本是TypeScript 2.0(尽管已在最新开发的版本中实现)。

有关详细信息,请参见此处

暂无
暂无

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

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