TypeScript 带有一个 interface ThisType。我找不到太多关于它的文档,所以我想知道:它有什么用?我如何使用它?它是如何工作的?
Tyl*_*rch 14
ThisType记录在这里:https : //www.typescriptlang.org/docs/handbook/utility-types.html#thistypet(感谢@axiac 在评论中链接)
但是,文档使用的示例对我来说有点令人费解。这是我发现的最简单的思考方式:
如果添加& ThisType<WhateverYouWantThisToBe>到对象的类型,则该对象中的函数将具有WhateverYouWantThisToBe用于this. 如果您不能通过this普通的 TypeScript 机制(它不是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);
Run Code Online (Sandbox Code Playgroud)
正如我在上面的评论中指出的那样,TypeScript 现在知道正确的类型,如果我们滥用它会出错。
请注意,与 TypeScript 的所有类型一样, usingThisType对生成的 JavaScript 代码没有影响。必须有代码的其他地方,以确保当成员helperFunctions被调用,适当的this值被设置(例如,通过使用Function.bind,Function.apply,Function.call等)
| 归档时间: |
|
| 查看次数: |
2139 次 |
| 最近记录: |