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

标签 javascript types module google-closure-compiler

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

./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 库的闭包 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"),
};

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. 在 externs 文件中声明 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 而您真正想要的是构造函数本身。

关于javascript - 包含构造函数的对象的闭包编译器注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39610213/

相关文章:

javascript - 在 jquery 自动完成控件上按 escape

javascript - 如何找到用户在打字时正在搜索的值?

haskell - 在 Haskell 中匹配扑克牌的花色和等级

spring-mvc - 如何将通用集合类对象作为参数传递

javascript - 如何在nodejs内部调用导出函数?

适用于 Windows 的 Python DBM 模块?

javascript - contentEditable 字段用于在数据库输入时维护换行符

javascript - 如何关闭不同类中的 swipeabledrawer

class - 为什么无法通过 Type.getClass() 访问类的静态字段?

php - 使用 Phalcon PHP 框架的嵌套多模块应用程序?