Search code examples
typescriptthistypechecking

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


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)


Solution

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