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();
在externs中,試着做Foo.Module.prototype.Wheel = Foo.Wheel; –
註解「@type {!Foo.Wheel}」和「@return {!Foo.Wheel}」將不起作用,因爲第一個說對象是Foo.Wheel的一個實例,第二個說該函數返回那個例子。你不想要任何這些場景,你真正想要的是構造函數。 另一種選擇是使用類型{function(new:!Foo.Wheel)},它表示該函數實際上是一個實例化Foo.Wheel對象的構造函數。 –
不錯,謝謝。 '@type {function(new:Foo.Wheel)}'沒有驚歎號。如果你想寫一個答案,我會接受它,或者我可以在一兩天內寫出答案。 – Joe