Skip to content

How to describe classes with statics in a return type #4303

@KimlikDAO-bot

Description

@KimlikDAO-bot

Say I want a factory which returns a class with certain static members. How can I write the return type? The constructor shape can be described by function(new: Type, args), but what if we also want to specify some static members?

To demonstrate, we'll define an interface for 2d Points. makeHorizontalLine() will return a Point class, with a static member Intercept.

/** @interface */
class Point { /** @type {number} */ x; /** @type {number} */ y; }

/**
 * @param {number} y
 * @return {typeof PointShape}
 */
function makeHorizontalLine(y) {
  return /** @type {typeof PointShape} */(
    /** @implements {Point} */
    class {
      /** @param {number} x */
      constructor(x) {
        this.x = x;
        this.y = y;
      }
      static Intercept = new this(0);
    }
  )
}

class PointShape {
  /** @param {number} x */
  constructor(x) { }
  /** @type {Point} */
  static Intercept; // where this line intersects the x=0 line
}

This one seems to work but it's quite indirect, requires a cast and I'm not sure if it's sound for property mangling. In typescript an interface containing a constructor type (function(new: Type, args)) is understood as describing the shape of the class, not the instances. What options are there in Google Closure?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions