在JSDOC中记录泛型类型参数

Seb*_*ian 13 javascript jsdoc webstorm

JSDoc存在记录的确切类型的数组的内容的可能性这样的:

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

这使得像WebStorm这样的IDE中的代码完成实际上提供了正确的类型信息[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(){}
Run Code Online (Sandbox Code Playgroud)

这个语法或功能不适用于我的IDE,这里没有列出,所以我想知道这个用例的语法是用于WebStorm还是任何其他JS创作工具.

len*_*ena 18

您可以尝试使用@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];  
}; 
Run Code Online (Sandbox Code Playgroud)

WebStorm使用此标记进行类型提示 - 即如果我们在上面的示例中将字符串数组传递给goog.array.find,IDE将知道返回类型是字符串,因此将建议字符串完成选项等.

不确定这是否是您正在寻找的...看起来相关的帖子就在这里.


Seb*_*ian 12

与此同时,对此功能的支持已经完成,现在记录在Closure Compiler JSDOC页面上.

基本上它是这样的:

/** @template T */
class Foo {
  /** @return {T} */
  get() { ... };

  /** @param {T} t */
  set(t) { ... };
}
Run Code Online (Sandbox Code Playgroud)

/**
 * @constructor
 * @template T
 */
Foo = function() { ... };
Run Code Online (Sandbox Code Playgroud)

不幸的是,在撰写本文时,WebStorm 7.0 不支持此功能(投票给它!).