在使用 TypeScript 的绑定函数中未正确识别“thisArg"上下文 [英] 'thisArg' context not correctly recognized in bound function with TypeScript

查看:50
本文介绍了在使用 TypeScript 的绑定函数中未正确识别“thisArg"上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With the below code, TypeScript won't recognize the context of thisArg (which should be a and should have saySomething() method. is there another way to give context of thisArg for 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,但类型检查显示

the console correctly logs Hello, but the the type checking is saying

属性saySomething"在类型B"上不存在.(2339)

推荐答案

这个答案解决了我的问题.

基本上,我必须

通过添加它(及其类型)在任何函数中更改 this 的上下文作为函数的第一个参数.

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).

In my case, I had to change saySomethingMyself method from saySomethingMyself() to 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());

这篇关于在使用 TypeScript 的绑定函数中未正确识别“thisArg"上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆