javascriptconstructorstatic-methodsjsdocanonymous-class

JSDoc: how to hint this.constructor.staticSomething?


I am calling a static method from the constructor of an anonymous javascript class using this.constructor.coords(), but the returned type is not being recognized correctly. It is treated as any.

I know I can cast just cast it manually as {x: number; y: number;}[], but I wonder if there is a smarter way to make VSCode/JSDoc just notice that the type of this.constructor.something must be that of the corresponding static method or property. Alternatively, I wonder if it is possible in JSDoc to cast this.cls = this.constructor with the anonymous class type (without giving it a name), because that would solve the problem for this.constructor.something as well.

MyAnonymousClass = class {

  static coords(){
    return [{x:0, y:1}, {x:1, y:0}, {x:-1, y:-1}];
  }
  /* type of coords (on mouse hover in vsCode):
    (method) MyAnonymousClass.coords(): {
      x: number;
      y: number;
    }[] */ // (CORRECT)

  constructor(){
    const x = this.constructor.coords();
    // type of x (on mouse hover in vsCode): any // (INCORRECT)

  }
}
AnotherAnonymousClass = class extends MyAnonymousClass{
  static coords(){
    return [{x:0, y:2}, {x:-2, y:0}];
  }
}

Solution

  • The following should do the trick. I've just wrapped the class declaration around an IIFE so it's never accessible outside. It's like an anonymous class.

    const MyAnonymousClass = (() => {
        return class _ {
            static coords() {
                return [{ x: 0, y: 1 }, { x: 1, y: 0 }, { x: -1, y: -1 }];
            }
    
            constructor() {
                const x = /** @type {typeof _} */(this.constructor).coords();
            }
    
            foo() { }
        }
    })();
    
    const AnotherAnonymousClass = class extends MyAnonymousClass {
        static coords() {
            return [{ x: 0, y: 2 }, { x: -2, y: 0 }];
        }
    }
    

    Screenshot