node.js指挥官:variadic选项的默认值?
我想拥有一个带有默认值的variadic选项,但是我只能输入一个默认值:
const program = new Command("ingest");
program
.option("-e, --extensions <ext...>", "file extensions to load", "dat")
.parse(process.argv);
const options = program.opts();
这样可以工作,默认值为“ dat”
。 但是,如果默认值是多个字符串的数组,例如[“ dat”,“ txt”]
,该怎么办?
我发现的第一个解决方案是不要放置默认设置,然后,如果options.extensions
不确定,请加载默认数组。这有效,但显然默认值未出现在帮助中。
解决这个小问题的第二个解决方案是将默认值作为空格分离字符串输入:
program.option("-e, --extensions <ext...>", "file extensions to load", "dat txt");
然后:
if(typeof options.extensions === "string")
options.extensions = options.extensions.split(" ")
此方式options.extensions
始终是字符串数组。
.addoption(new Option())
在这里有帮助吗?不幸的是,除了提供的三个示例外,我还找不到option
类的文档。
谢谢! 马里奥
I want to have a variadic option with defaults, but I could enter only one value as default like this:
const program = new Command("ingest");
program
.option("-e, --extensions <ext...>", "file extensions to load", "dat")
.parse(process.argv);
const options = program.opts();
This works and the default is "dat"
.
But what should I do if the default is an array of multiple strings like ["dat", "txt"]
?
The first solution that I found is to not put a default and then, if options.extensions
is undefined, load it with the default array. This works but obviously the default does not appear in the help.
The second solution that solves this small problem is to enter the default as a space separated string:
program.option("-e, --extensions <ext...>", "file extensions to load", "dat txt");
and then:
if(typeof options.extensions === "string")
options.extensions = options.extensions.split(" ")
This way options.extensions
is always an array of strings.
Could .addOption(new Option())
help here? Unfortunately I cannot find documentation for the Option
class besides the three examples provided.
Thanks!
mario
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认值不必是字符串。使用数组,它甚至可以简化以后的代码,因为选项值始终是数组。
TypeScript 已更新,在 Commander v9.3.0 中允许的类型中包含
string[]
。The default does not have to be a string. Use the array, and it might even simplify your later code since the option value will always be an array.
TypeScript updated to include
string[]
in allowed types in Commander v9.3.0.我发现的将数组默认值添加到可变参数选项的最对打字稿友好的方法是:
希望它有帮助
The most Typescript-friendly way to add an array default to a variadic option I have found is:
Hope it helps