0

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

J F
  • 631
  • 7
  • 15
  • 2
    You cannot express that requirement with TS type system. – zerkms Sep 14 '17 at 08:22
  • Which part exactly is the library code? Is this `A` class part of it? – Nitzan Tomer Sep 14 '17 at 08:26
  • @NitzanTomer nope, I own `A`. Think of that being the wrapper of the library code. – J F Sep 14 '17 at 10:42
  • 1
    As @zerkms wrote there's no way for you to restrict this in typescript, you can change the `A.method` to receive another (optional) `thisArg` param and then bind the callback. Then it should be clear that the passed in callback should be either bound already (using `bind` or arrow function) or you can pass the extra param. – Nitzan Tomer Sep 14 '17 at 10:45
  • @NitzanTomer yeah, that's actually what I'm doing now as a workaround. OK, thank you all! – J F Sep 14 '17 at 12:08

0 Answers0