2

我试图检查返回构造函数对象的库。用下面的代码关闭错误:包含构造函数的对象的闭包编译器注释

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

下面的代码结构:

我-APP-code.js - 该代码我使用

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

externs- foo.js - Foo库的关闭extern

/** @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"), 
}; 

富/ 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(); 
+0

在externs中,试着做Foo.Module.prototype.Wheel = Foo.Wheel; –

+1

注解“@type {!Foo.Wheel}”和“@return {!Foo.Wheel}”将不起作用,因为第一个说对象是Foo.Wheel的一个实例,第二个说该函数返回那个例子。你不想要任何这些场景,你真正想要的是构造函数。 另一种选择是使用类型{function(new:!Foo.Wheel)},它表示该函数实际上是一个实例化Foo.Wheel对象的构造函数。 –

+0

不错,谢谢。 '@type {function(new:Foo.Wheel)}'没有惊叹号。如果你想写一个答案,我会接受它,或者我可以在一两天内写出答案。 – Joe

回答

2

我知道两个解决这个问题的:

  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一个实例,你真正想要的是构造本身。

相关问题