2013-04-15 37 views
7

JSDoc存在的可能性來記錄的確切類型的數組的內容like this文獻一般類型參數

/** @param {Array.<MyClass>} myClasses An array of MyClass objects. */ 
TestClass.protoype.someMethod = function(myClasses){ 
    myClasses[0].aMethodOnMyClass(); 
} 

這使得代碼完成在IDE的像WebStorm實際提供[0].後的權利類型的信息。這適用於Array類型,但是我也有我自己的集合類型,我也想使用此功能。問題是我無法找到正確的語法(也許是因爲沒有)。我希望能夠以某種方式宣佈我的課是這樣的:

/** 
* @typeparam {T} the type parameter 
* @constructor {Test2.<T>} 
* */ 
Test2 = function(){}; 

/** 
* @returns {T} a value of type T, where T is the generic type parameter of Test2 
*/ 
Test2.prototype.getGenericValue = function(){} 

這句法或功能不與我的IDE工作,並沒有列出here,所以我想知道是否有這個使用 - 語法情況下,無論是WebStorm還是其他任何JS創作工具。

回答

4

與此同時,對此功能的支持已完成,現在已記錄在the Closure Compiler JSDOC page上。

基本上是這樣的:

/** 
* @constructor 
* @template T 
*/ 
Foo = function() { ... }; 

/** @return {T} */ 
Foo.prototype.get = function() { ... }; 

/** @param {T} t */ 
Foo.prototype.set = function(t) { ... }; 

不幸的是,在寫作的時候,WebStorm 7.0 does not support this feature (Vote for it!),但。

11

您可以嘗試使用@template標記(Google Closure庫中使用的未公開標記 - 非常有限的泛型)。喜歡的東西:

/** 
* Search an array for the first element that satisfies a given condition and 
* return that element. 
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array 
*  like object over which to iterate. 
* @param {?function(this:S, T, number, ?) : boolean} f The function to call 
*  for every element. This function takes 3 arguments (the element, the 
*  index and the array) and should return a boolean. 
* @param {S=} opt_obj An optional "this" context for the function. 
* @return {T} The first array element that passes the test, or null if no 
*  element is found. 
* @template T,S 
*/ 
goog.array.find = function(arr, f, opt_obj) {  
    var i = goog.array.findIndex(arr, f, opt_obj);  
    return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i]; 
}; 

WebStorm使用該標籤的類型提示 - 也就是說,如果我們通過上面的字符串樣品中的goog.array.find的陣列,IDE會知道,返回類型爲字符串,因此字符串完成選項會被建議等

不知道這是你在找什麼...看起來相關的帖子是here

+0

謝謝,我只是發現了這一點,我自己從[這個YouTrack問題(http://youtrack.jetbrains.com/issue/WEB- 1208)和[此Closure編譯器更改集](https://code.google.com/p/closure-compiler/source/detail?spec=svn64d22457ddca24b07370f711276a449273bd6330&r=0eb41cabc9ba5463e3a34ea2fd900a8dd54f2136)。在課堂上是否有這種支持?我的測試表明,這隻適用於「函數本地類型參數」。 – Sebastian

0

下面的代碼工作正常,我在WebStorm 8

/** @type {Array.<MyPair.<Event, Array.<Thought>>>} */ 
scope.pairs = []; 

/** 
* @template TFirst, TSecond 
*/ 
function MyPair(first, second){ 
    this.first = first; 
    this.second = second; 
} 
/** @type {TFirst} */ 
MyPair.prototype.first = null; 
/** @type {TSecond} */ 
MyPair.prototype.second = null; 

... 
function Event(){} 
... 
... 
function Thought(){} 
... 
+0

在上面的例子中,它也和Event和Thought對象一起工作。 –

+1

是的,同時在WS8中已經實現了很多功能,但仍然存在一些未解決的問題,這些問題只能在WS9中解決 - 請參閱我的答案和相關問題。 – Sebastian