包含构造函数的对象的闭包编译器注释

Closure compiler annotations for an object containing a constructor function

我正在尝试对 returns 构造函数对象的库进行类型检查。使用以下代码关闭错误:

./my-app.js:11: ERROR - Cannot call non-function type Foo.Wheel
const wheel = new Foo.Wheel();
               ^

代码结构如下:

my-app-code.js - 我正在使用的代码

const Foo = /** @type{!Foo.Module} */ require('foo');
const wheel = new Foo.Wheel();
wheel.rotate();

externs-foo.js - Foo 库的闭包 externs

/** @const */
const Foo = {};


/** @record */
Foo.Module = function() {};

/** @type {!Foo.Wheel} */
Foo.Module.prototype.Wheel;

/** @constructor */
Foo.Wheel = function() {};

/**
* @returns {void}
*/
Foo.Wheel.prototype.rotate = function() {};

foo/index.js - 对应于 Foo.Module 类型。

module.exports = {
  Wheel: require("./wheel"),
};

foo/wheel.js - 对应于 Foo.Wheel.

function Wheel() {}

Wheel.prototype.rotate = function() {};

module.exports = Wheel;

我在 externs-foo.js 上尝试了一种变体,结果如下。

使Foo.module.prototype.Wheel成为函数

/** @return {!Foo.Wheel} */
Foo.Module.prototype.Wheel = function() {};

错误:

my-app.js:11: ERROR - Expected a constructor but found type function(this:Foo.Module):Foo.Wheel.
const wheel = new Foo.Wheel();

my-app.js:13: ERROR - Property rotate never defined on module$myapp_Foo of type Foo.Module
wheel.rotate();

我知道这个问题有两种解决方案:

  1. 正在外部文件中声明 Foo.Module.prototype.Wheel = Foo.Wheel;
  2. 使用@type {function(new:Foo.Wheel)},表示该函数实际上是一个实例化Foo.Wheel对象的构造函数。

我更喜欢解决方案 #1,因为它声明了对构造函数的引用,因此编译器将允许我访问构造函数的属性(例如静态方法)。 IIRC 这不能在解决方案 #2 中完成。

注释 @type {!Foo.Wheel}@return {!Foo.Wheel} 将不起作用,因为它们引用了 Foo.Wheel 的实例,而您真正想要的是构造函数本身。