I'm facing a typescript error when compiling the following exemple:

class A {
  public static then() {
    return this;
  }
}

class B extends A {
  public static shouldWorks() { return 42; }
}

console.log(B.then().shouldWorks());

the compiler returns:

error TS2339: Property 'shouldWorks' does not exist on type 'typeof A'.

but when I try to execute the compiled script, it works !

what's wrong ?

1 Answers

1
Titian Cernicova-Dragomir On Best Solutions

this in static methods is not polymorphic. So this will just be typeof A when returning the class from then, and thus the methods added in B will have no impact on this class.

You can simulate polymorphic this by adding a type for the this parameter. The type of this will be a type parameter inferred from the call site:

class A {
    public static then<TThis extends new (...a: any[]) => A>(this: TThis) {
        return this;
    }
}

class B extends A {
    public static shouldWorks() { return 42; }
}

console.log(B.then().shouldWorks());