TypeScript function parameter signature - allow arrow function, disallow class method

326 Views Asked by At

Say that I have this class that wraps some other library:

class A {
    method(callback: () => void): void {
        // ...
    }
}

and this one using it:

class B {
    a: A;

    constructor() {
        this.a = new A();
    }

    do(): void {
        this.a.method(this.doLater);
        this.a.method(() => this.doLater());
    }

    doLater(): void {
        // ...
    }
}

Both of the calls inside B.do() compile, but the first one fails at runtime because of lost this context when it tries to call doLater(). Understandable. Not much I can do about that, but I'd like to be able to write the A.method() signature so that you are forced to use an arrow function at the call site, since I can't modify the library code. Is that possible?

I'm using TypeScript 2.5.2 and --noImplicitThis is enabled

0

There are 0 best solutions below