jsdoc 和 vscode:记录作为参数传递给另一个函数的函数

jsdoc and vscode: Documenting a function passed as an argument to another function

我试图在 javascript 中记录函数的输入参数,但我不知道如何在 jsdoc 中进行。

我查看了 jsdoc 文档,它建议使用 @callback 注释是必需的,但是 Visual Studio 代码 (vscode) 没有按照截图。

location 参数的智能感知显示它是 any 类型而不是 locator 类型(参数为 id 的函数 returns一个Location).

显示调用作为参数传递的函数的函数的示例代码:

class Location {
  constructor(position, count) {
    this.position = position;
    this.count = count;
  }
}

const items = {
  'USB Cable': new Location('Desk Drawer', 123),
  Keyboard: new Location('Desk Surface', 1),
};

/**
 * A locater.
 * @param {string} id 
 * @returns {Location}
 */
const locaterA = id => items[id];

/**
 * Finds the item by its unique id.
 * @callback locater
 * @param {string} id
 * @returns {Location}
 */

/**
 * Attempt to find the item with the given locater.
 * @param {string} id 
 * @param {locater} locater
 */
const locate = (id, locater) => locater(id);

const result = locate('USB Cable', locaterA);

console.log(result);

这是我正在做的事情的问题,vsdoc 不支持用例,还是 vscode 不支持它?

根据 JSDoc 本身,您似乎在正确使用它。但是,看起来 Visual Studio 可能只支持 JSDoc 的有限子集,其中不包括 @callbackhttps://msdn.microsoft.com/en-us/library/mt162307.aspx

我手边没有 Visual Studio,但您可以尝试 Google 关闭样式,也就是这样做:

@param { function(string) : number } locator

这是一个接受字符串和 returns 数字的函数。

您可以在此处找到该文档:https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler(搜索 "Function Return Type" 以跳转到相关部分)。

我至少注意到 JetBrains 支持该语法。

Edit: vscode seems to be supporting @callback starting from TypeScript 2.9

Vscode 的 IntelliSense 不支持 @callback。正在此处对其进行跟踪:https://github.com/Microsoft/TypeScript/issues/7515

作为一种方便的解决方法,您可以使用 @typedef:

/**
 * Finds the item by its unique id.
 * @typedef {function(string): Location} Locater
 */

/**
 * Attempt to find the item with the given locater.
 * @param {string} id 
 * @param {Locater} locater
 */
const locate = (id, locater) => locater(id);