TypeScript 用例
TypeScript 定义需要考虑 yargs 的 type
以及 demandOption
/ default
的存在。
下面是一个 .options()
的定义
#!/usr/bin/env node
@@ -22,7 +23,7 @@ const argv = yargs.options({
}).argv;
argv
的类型应该如下:
{
@@ -35,60 +36,12 @@ const argv = yargs.options({
f: string | undefined;
_: string[];
$0: string;
} | Promise<{
[x: string]: unknown;
a: boolean;
b: string;
c: number | undefined;
d: (string | number)[] | undefined;
e: number;
f: string | undefined;
_: string[];
$0: string;
}>
正如你看到的,argv
的类型是一组参数和可以被解析为这组参数对 Promise
的 Union
类型。这样做的原因是,在 argv
中,可以使用 command
,而 command
如果是异步的,解析器将在命令完成后进行解析。
之所以使用 Union
类型,是因为当你调用 .argv
时,yargs 并不知道你是否使用了异步的命令,所有两种可能都有。
但这可能会导致访问属性时发生错误。
const argv = yargs(process.argv.slice(2)).options({
a: { type: 'boolean', default: false },
...
}).argv;
argv.a // => Property 'a' does not exist on type...
所以,当你知道你的程序中没有使用异步命令时,你可以使用 parseSync
const argv = yargs(process.argv.slice(2)).options({
a: { type: 'boolean', default: false },
...
}).parseSync();
argv.a // => No error, type: boolean
}
相反,如果你使用了异步命令,则需要使用 await
:
const parser = yargs(process.argv.slice(2)).options({
a: { type: 'boolean', default: false },
...
});
(async() => {
const argv = await parser.argv;
argv.a // => No error, type: boolean
})();
你可能会为你的应用定义一个 interface
,用来描述解析后的 argv
。
interface Arguments {
@@ -101,32 +54,18 @@ interface Arguments {
f: string | undefined;
}
如果你需要使用 .wrap()
和 .terminalWidth()
,你需要先创建 yargs 实例。
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
// ...
const yargsInstance = yargs(hideBin(process.argv));
cosnt args = yargsInstance
.wrap(myYargs.terminalWidth())
// .otherMethods(...)
.argv
更具体的 choices() 类型
为了改进 choices
选项的类型,你也可以指定其类型。
To improve the choices
option typing you can also specify its types:
type Difficulty = 'normal' | 'nightmare' | 'hell';
const difficulties: ReadonlyArray<Difficulty> = ['normal', 'nightmare', 'hell'];
const argv = yargs.option('difficulty', {
choices: ["normal", "nightmare", "hell"] as const,
choices: difficulties,
demandOption: true
}).argv;
argv.difficulty
的类型为 'normal' | 'nightmare' | 'hell'
。
argv
will get type 'normal' | 'nightmare' | 'hell'
.