在JSDoc中记录析构函数参数

mor*_*kro 52 arguments destructuring jsdoc ecmascript-6

以前我总是记录我的对象参数如下:

/**
 * Description of the function
 *
 * @param {Object} config - The configuration
 * @param {String} config.foo
 * @param {Boolean} [config.bar] - Optional value
 * @return {String}
 */
function doSomething (config = {}) {
  const { foo, bar } = config;
  console.log(foo, bar);
  // do something
}
Run Code Online (Sandbox Code Playgroud)

但我不确定desctructured函数参数的最佳方法是什么.我是否只是忽略了对象,以某种方式定义它或者记录它的最佳方式是什么?

/**
 * Description of the function
 *
 * @param {String} foo
 * @param {Boolean} [bar] - Optional value
 * @return {String}
 */
function doSomething ({ foo, bar } = {}) {
  console.log(foo, bar);
  // do something
}
Run Code Online (Sandbox Code Playgroud)

我觉得我上面的方法并没有明确表明函数需要一个object而不是两个不同的参数.

我能想到的另一种方法是使用@typedef,但这可能最终成为一个巨大的混乱(特别是在一个有很多方法的大文件中)?

/**
 * @typedef {Object} doSomethingConfiguration
 * @property {String} foo
 * @property {Boolean} [bar] - Optional value
 */

/**
 * Description of the function
 *
 * @param {doSomethingConfiguration}
 * @return {String}
 */
function doSomething ({ foo, bar } = {}) {
  console.log(foo, bar);
  // do something
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 49

正如文档中所述,这就是它的意图.

/**
 * My cool function.
 *
 * @param {Object} obj - An object.
 * @param {string} obj.prop1 - Property 1.
 * @param {string} obj.prop2 - Property 2.
 */
var fn = function ({prop1, prop2}) {
  // Do something with prop1 and prop2
}
Run Code Online (Sandbox Code Playgroud)

所以,你的第一个例子非常正确.

另一个更深层嵌套的例子:

/**
 * Nesting example.
 *
 * @param {object} param
 * @param {number} param.a - First value
 * @param {object} param.b - Wrapper
 * @param {number} param.b.c - Second value
 * @return {number} sum a and b
 */
letters = ({a, b: {c}}) => a + c;
Run Code Online (Sandbox Code Playgroud)

  • 哎呀。`({a: b}, {a}))` 或 `({a}, {b})` - 要点是 JSDoc `@param` 标签是无序的 AFAIK,并且如果 JSDoc 尝试,键可能不明确使用属性名称进行匹配。VSCode 的下一版本将使用位置查找来解决这种情况。 (2认同)

Cod*_*gar 18

我个人使用这个:

/**
* @param {{
  a: number
  b: number
}} param0
* @returns {number} The sum
*/
const func = ({ a, b }) => a + b;
Run Code Online (Sandbox Code Playgroud)

只需在那里创建对象。

我也利用了 TypeScript,并且会声明 obtional basb?b: number | undefinedas JSDoc 也允许联合


Jak*_*olý -8

请参阅JSDoc 的“记录参数的属性”

/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function(employee) {
    // ...
};
Run Code Online (Sandbox Code Playgroud)

Google Closure 编译器类型检查,基于但源自 JSDoc,也允许@param {{x:number,y:number}} point A "point-shaped" object.

  • 这并没有回答问题 - 这个例子没有使用解构!通过解构,你没有父对象。 (9认同)
  • 他不是已经在这么做了吗?他问现在函数中不再有“employee”变量该怎么办。 (2认同)