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

谁说胖子不能爱 提交于 2020-12-31 05:40:55

问题


I'm trying to document the input parameters to a function in javascript, but I can't work out how to do it in jsdoc.

I've looked at the jsdoc documentation which suggests that using the @callback comment is what's required, but Visual Studio Code (vscode) doesn't highlight it as per the screenshot.

The intellisense for the location parameter shows that it's type any rather than of type locator (a function with a parameter of id which returns a Location).

Example code which shows a function calling a function passed as a parameter:

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);

Is this a problem with what I'm doing, vsdoc not supporting the use case, or vscode not supporting it?


回答1:


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

Vscode's IntelliSense doesn't support @callback. It's being tracked here: https://github.com/Microsoft/TypeScript/issues/7515.

As a convenient workaround you can use @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);




回答2:


It looks like you're using it correctly, per JSDoc itself. However, it looks like Visual Studio may only support a limited subset of JSDoc, which doesn't include @callback: https://msdn.microsoft.com/en-us/library/mt162307.aspx

I don't have Visual Studio handy, but you might try the Google Closure style, which is to do it like this:

@param { function(string) : number } locator

This says that it's a function that takes a string, and returns a number.

You can find that documentation here: https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler (search for "Function Return Type" to jump to the relevant section).

I've noticed with JetBrains stuff at least, that it supports that syntax.



来源:https://stackoverflow.com/questions/46777262/jsdoc-and-vscode-documenting-a-function-passed-as-an-argument-to-another-functi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!