typescript - 方法调用的`this`强制
问题描述
我有一个简单的类,它有一个相应的namedA
实例。唯一的方法对(的范围)的范围有相当严格的要求。这个类真正做的就是打印出它为这个测试存储的数据。A
a
this
this
A
class A {
private _data: string;
constructor(data: string) {
this._data = data;
}
method(this: this): void {
console.log(this._data);
}
}
const a = new A("my_test");
function test_a(a: A): void {
a.method();
}
function test_b(f: () => void): void {
f();
}
function test_c(f: (this: void) => void): void {
f();
}
test_a(a); // [1] Perfectly fine
test_b(a.method); // [2] Not fine! Runs assuming `this` was bound to `a`'s this
test_b(a.method.bind(a)); // [3] Perfectly fine
test_c(a.method); // [4] Perfectly fine. Provides an error properly, but rather verbose
test_c(a.method.bind(a)); // [5] Perfectly fine. #4, but using bind properly
此测试旨在查找 #2 会导致不正确范围this
调用的编译时错误的配置。但是,事实并非如此。据我所知,test_b
假设this: any
. 根据该逻辑,标记为 #2 的行将隐式地将方法类型转换为(this: this)=>void
,(this: any)=>void
而不会引发编译时错误。
test_c
是我能找到的唯一一种可以this
在作为参数传入之前正确强制绑定的机制。
我真的不介意()=>void
假设this
是any
类型。但是,我不喜欢如何a.method
隐式类型转换为 type (this: any)=>void
。对我来说,这相当绕开一个相当重要的类型检查机制。另一种方法是显式指定每个接受可调用对象的函数和方法,并为this
. 实际上,这没有任何意义,因为它依赖于每个方法、自写代码和所有库实现,来明确定义this
每个回调的范围。
是否有tsconfig.json
防止这种类型强制的设置?
除了“不要那样做”之外,还有没有更好的方法来确保this
适当范围内的类型安全?
解决方案
推荐阅读
- git - 如何安全地与 master 切换分支?
- reactjs - Firestore 返回“未定义”
- mongodb - 如何使用多个 db ref 关系查询 mongo
- javascript - Gatsby — 错误:使用 gatsby-plugin-ffmpeg 请求 GraphQL 后找不到 ffprobe
- c# - Xamarin Forms 链接的 DLL 异常
- postgresql - 无法访问文件 wal2json 没有这样的文件或目录
- visual-studio-code - 打开文件夹时停止 vscode 打开以前的选项卡
- python - 将 If 语句添加到信号无法正常工作
- django-models - DRF - int() 参数必须是字符串、类似字节的对象或数字,而不是“DeferredAttribute”
- javascript - window.matchMedia 不是函数