Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

javascript - Document generic type parameters in JSDOC

In JSDoc there exists the possibility to document the exact types of array contents like this:

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

This makes code completion in IDEs like WebStorm actually provide the right type information after the [0].. This works well for the Array type, however I have my own collection types where I would like to make use of this feature, too. The problem is I cannot find the right syntax (maybe because there is none, yet). I would love to be able to declare my class somehow like this:

/**
 * @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(){}

This syntax or feature does not work with my IDE and is not listed here, so I am wondering whether there is a syntax for this use-case, either for WebStorm or any other JS authoring tool.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try using @template tag (undocumented tag used in Google Closure library - extremely limited form of generics). Something like:

/**   
 * 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 uses this tag for type hinting - i.e. if we pass array of strings to goog.array.find in the sample above , IDE will know that return type is string, so string completion options will be suggested etc.

Not sure if this is what you are looking for... The post that looks related is here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...