繁体   English   中英

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

[英]Closure compiler annotations for an object containing a constructor function

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

./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的实例,而您真正想要的是构造函数本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM