简体   繁体   English

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

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

I'm trying to typecheck a library that returns an Object of constructor functions.我正在尝试对返回构造函数对象的库进行类型检查。 With the following code Closure errors with:使用以下代码关闭错误:

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

Here's the code structure:下面是代码结构:

my-app-code.js - The code I'm using my-app-code.js - 我正在使用的代码

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

externs-foo.js - Closure externs for the Foo library 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 - corresponds to Foo.Module type. foo/index.js - 对应于 Foo.Module 类型。

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

foo/wheel.js - corresponds to Foo.Wheel. foo/wheel.js - 对应于 Foo.Wheel。

function Wheel() {}

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

module.exports = Wheel;

I tried one variation on externs-foo.js with the following results.我在externs-foo.js上尝试了一种变体,结果如下。

Make Foo.module.prototype.Wheel a function使Foo.module.prototype.Wheel成为一个函数

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

Errors with:错误:

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();

I'm aware of two solutions to this issue:我知道这个问题的两个解决方案:

  1. Declaring Foo.Module.prototype.Wheel = Foo.Wheel;声明Foo.Module.prototype.Wheel = Foo.Wheel; in the externs file.在外部文件中。
  2. Use @type {function(new:Foo.Wheel)} , which says that the function is in fact a constructor that instantiates a Foo.Wheel object.使用@type {function(new:Foo.Wheel)} ,它表示该函数实际上是一个实例化 Foo.Wheel 对象的构造函数。

I prefer solution #1 because it declares a reference to the constructor function, so the compiler will allow me to access properties of the constructor (eg static methods).我更喜欢解决方案#1,因为它声明了对构造函数的引用,因此编译器将允许我访问构造函数的属性(例如静态方法)。 IIRC this can't be done in solution #2. IIRC 这不能在解决方案#2 中完成。

The annotations @type {!Foo.Wheel} and @return {!Foo.Wheel} won't work because they refer to an instance of Foo.Wheel and what you actually want is the constructor itself.注释@type {!Foo.Wheel}@return {!Foo.Wheel}不起作用,因为它们引用Foo.Wheel的实例,而您真正想要的是构造函数本身。

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

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