首页 > 解决方案 > 方法调用的`this`强制

问题描述

我有一个简单的类,它有一个相应的namedA实例。唯一的方法对(的范围)的范围有相当严格的要求。这个类真正做的就是打印出它为这个测试存储的数据。AathisthisA

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假设thisany类型。但是,我不喜欢如何a.method隐式类型转换为 type (this: any)=>void。对我来说,这相当绕开一个相当重要的类型检查机制。另一种方法是显式指定每个接受可调用对象的函数和方法,并为this. 实际上,这没有任何意义,因为它依赖于每个方法、自写代码和所有库实现,来明确定义this每个回调的范围。

是否有tsconfig.json防止这种类型强制的设置?

除了“不要那样做”之外,还有没有更好的方法来确保this适当范围内的类型安全?

标签: typescript

解决方案


推荐阅读