有没有办法@callback在VS Code中使用jsDoc的标签?
我尝试了从回调标签的jsDoc 文档中截取的以下代码:
/**
* @class
*/
function Requester() {}
/**
* Send a request.
* @param {requestCallback} cb - The callback that handles the response.
*/
Requester.prototype.send = function(cb) {
// code
};
/**
* This callback is displayed as a global member.
* @callback requestCallback
* @param {number} responseCode
* @param {string} responseMessage
*/
Run Code Online (Sandbox Code Playgroud)
但是 VS Code 似乎没有正确解释标签,你的参数类型仍然存在,any并且函数的工具提示中没有提到回调定义。
是否有任何解决方法/插件可以启用此功能?
在撰写本文时,@callbackVSCode 不支持,但有解决方法(一旦 VSCode 支持回调,我将更新此答案以反映它们从哪个版本开始工作)。
请参阅此问题以跟踪进度:
2018 年 5 月 8 日编辑:刚刚提交了带有修复程序的拉取请求:
编辑 2018 年 5 月 17 日:修复已合并到 TypeScript 2.9.1 中,可能会出现在 VS Code 的下一个版本中
在线程的早期评论中@typedef建议了一个不完整的解决方法:
Run Code Online (Sandbox Code Playgroud)/** * @typedef {function(number)} addedCallback */ /** *@param {addedCallback} a */ var add = function (a) { }
然而,正如后来的一些评论所指出的:
真正的用途
@callback是正确描述回调的所有参数,有时是期望的返回值及其对当前函数的影响。
该评论还为两个选项提供了更完整的解决方法:创建一个虚拟函数,或记录回调本身。
如果您使用像 Webpack 这样的构建工具,并设置它以消除未使用的变量和函数,“虚拟”函数将不会显示您的生产代码。
以下是基于我自己的代码的两种解决方法的示例:
/**
* A compare function to pass to `indices.sort()`, see also:
* [`TypedArray.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/sort).
*
* @param {number} i
* @param {number} j
*/
function indexCompareFunction(i, j) {
// dummy function for missing VSCode JSDoc callback support
return i - j;
}
// Explicit
/**
* Creates a compare function to sort a _separate_ array
* of indices, based on lexicographical ordering of
* the array values. Produces a stable sort.
* @param {*[]} array
* @returns {indexCompareFunction}
*/
function baseCompareFunc(array) {
return (i, j) => {
let vi = array[i],
vj = array[j];
return vi < vj ?
-1 : vi > vj ?
1 : i - j;
};
}
// Inferred from callback JSDoc
/**
* @param {*[]} array
*/
function baseCompareFunc2(array) {
// Must store the function in a variable,
// otherwise JSDoc does nothing!
/**
* @param {number} i
* @param {number} j
*/
let compareFunc = (i, j) => {
let vi = array[i],
vj = array[j];
return vi < vj ?
-1 : vi > vj ?
1 : i - j;
};
return compareFunc;
}
Run Code Online (Sandbox Code Playgroud)
编辑:还有另一个更短的解决方法,它依赖于 VSC 的 TypeScript 支持。从技术上讲,它不是“标准”的 JSDoc。自己决定这是否重要。正如其中一位开发人员所解释的那样:
在 { .. } 中,我们允许使用 TypeScript 类型语法,这就是您在 TS 中定义调用签名的方式。
/**
* Creates a compare function for sorting a set of *indices*
* based on lexicographical comparison of the array values
* @param {*[]} array
* @returns {{(i:number, j:number)=> number}}
*/
function baseCompareFunc(array) {
return (i, j) => {
let vi = array[i],
vj = array[j];
return vi < vj ?
-1 :
vi > vj ?
1 :
i - j; // the part that makes this a stable sort
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2346 次 |
| 最近记录: |