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

只愿长相守 提交于 2021-01-29 20:57:03

问题


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?

The code:

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());

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

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


回答1:


I think this is too confusing for the linter, I rather would play with inheritance. I just suggest you to cast as any , because cast as "A" type won't work :

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



回答2:


This answer solved my issue.

Basically, I had to

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

In my case, I had to change saySomethingMyself method from saySomethingMyself() to saySomethingMyself(this: A).

Complete updated code:

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());



回答3:


You need to annotate the this type for your method.

saySomethingMyself(this: A) {

Full solution:

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



来源:https://stackoverflow.com/questions/62954376/thisarg-context-not-correctly-recognized-in-bound-function-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!