【发布时间】:2016-08-23 08:13:57
【问题描述】:
以前我总是将我的对象参数记录如下:
/**
* 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
}
但我不确定使用 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
}
我觉得我上面的方法并没有表明该函数需要一个 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
}
【问题讨论】:
-
我认为第一种方法还是可以的。没有人关心对象在您的代码中是否命名为
config或是否有任何名称。 -
在 WebStorm 中,我发现如果我只描述(解构后)参数而忽略解构,除了不太常见的情况外,它大部分都有效。所以在你的例子中,描述两个参数
foo和bar。这不是最终解决方案,但任何使用对象的方法都会产生检查错误——我最关心的是来自 IDE 的检查和自动完成。
标签: arguments ecmascript-6 jsdoc destructuring