什么是TypeScript的ThisType用于?

问题描述 投票:1回答:1

TypeScript带有ThisType接口。我找不到很多关于它的文档,所以我想知道:它用于什么?我该如何使用它?它是如何工作的?

typescript
1个回答
1
投票

ThisType记录在这里:https://www.typescriptlang.org/docs/handbook/utility-types.html#thistypet(感谢@axiac在评论中链接)

但是,文档使用的示例对我来说有点令人费解。这是我发现思考它的最简单方法:

如果将& ThisType<WhateverYouWantThisToBe>添加到对象的类型,则该对象中的函数将使用WhateverYouWantThisToBe作为this的类型。如果你不能通过普通的TypeScript机制(它不是this等)指定class应该是什么,这是有帮助的。

如果我们想象一个我们正在编写一些注册一些辅助函数的代码的世界,你可以像这样写:

interface HelperThisValue {
    logError: (error: string) => void;
}

let helperFunctions: { [name: string]: Function } & ThisType<HelperThisValue> = {
    hello: function() {
        this.logError("Error: Something went wrong!"); // TypeScript successfully recognizes that "logError" is a part of "this".
        this.update(); // TS2339: Property 'update' does not exist on HelperThisValue.
    }
}

registerHelpers(helperFunctions);

正如我在上面的评论中指出的那样,TypeScript现在知道正确的类型,如果我们误用它就会出错。

请注意,与所有TypeScript的类型一样,使用ThisType对生成的JavaScript代码没有影响。其他地方必须有代码确保当helperFunctions的成员被调用时,设置正确的this值(例如通过使用Function.bindFunction.applyFunction.call等)

© www.soinside.com 2019 - 2024. All rights reserved.