'thisArg' 使用 TypeScript 在绑定函数中无法正确识别上下文

'thisArg' context not correctly recognized in bound function with TypeScript

使用下面的代码,TypeScript 将无法识别 thisArg 的上下文(应该是 a 并且应该有 saySomething() 方法。是否有另一种方法可以给出上下文thisArg 用于 TypeScript?

代码:

class A {
    saySomething() {
        console.log('Hello!');
    }
}

class B {
    constructor(a: A) {
        const boundSaySomething = this.saySomethingMyself.bind(a);
        boundSaySomething();
    }

    saySomethingMyself() {
        this.saySomething();
    }
}

const test = new B(new A());

控制台正确记录 Hello,但类型检查显示

Property 'saySomething' does not exist on type 'B'.(2339)

我认为这对 linter 来说太混乱了,我宁愿玩继承。 我只是建议你转换为 any ,因为转换为“A”类型是行不通的:

saySomethingMyself() {
    (<any>this).saySomething();
}

解决了我的问题。

基本上,我不得不

change the context of this in any function by adding it (and its type) as the first argument to the function.

在我的例子中,我不得不将 saySomethingMyself 方法从 saySomethingMyself() 更改为 saySomethingMyself(this: A)

完成更新代码:

class A {
    saySomething() {
        console.log('Hello!');
    }
}

class B {
    constructor(a: A) {
        const boundSaySomething = this.saySomethingMyself.bind(a);
        boundSaySomething();
    }

    saySomethingMyself(this: A) {
        (this).saySomething();
    }
}

const test = new B(new A());

您需要为您的方法注释 this 类型。

saySomethingMyself(this: A) {

完整解决方案:

class A {
    saySomething() {
        console.log('Hello!');
    }
}

class B {
    constructor(a: A) {
        const boundSaySomething = this.saySomethingMyself.bind(a);
        boundSaySomething();
    }

    saySomethingMyself(this: A) {
        this.saySomething();
    }
}

const test = new B(new A());

Playground