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

a-h*_*a-h 5 javascript node.js jsdoc visual-studio-code

我正在尝试用 javascript 记录函数的输入参数,但我无法在 jsdoc 中弄清楚如何做到这一点。

我查看了 jsdoc 文档,它表明使用@callback注释是必需的,但 Visual Studio Code (vscode) 没有按照屏幕截图突出显示它。

location参数的智能感知显示它是类型any而不是类型locator(带有参数的函数id返回 a 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);
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lex 7

编辑:vscode 似乎支持@callback从 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);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


sam*_*ime 5

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

我没有方便的 Visual Studio,但你可以尝试 Google Closure 风格,如下所示:

@param { function(string) : number } locator
Run Code Online (Sandbox Code Playgroud)

这表示它是一个接受字符串并返回数字的函数。

您可以在这里找到该文档: https: //github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler(搜索“函数返回类型”以跳转到相关部分)。

我至少注意到 JetBrains 的东西,它支持这种语法。