![](/img/trans.png)
[英]Closure Compiler EXTERNS for PIXI.js - custom object parameter annotations
[英]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();
我知道這個問題的兩個解決方案:
Foo.Module.prototype.Wheel = Foo.Wheel;
在外部文件中。@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.