简体   繁体   中英

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

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?

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM