使用 yargs 和 typescript 属性不存在

Pab*_*abo 3 typescript yargs

我正在尝试用打字稿中的 yargs 解析命令行,但它不起作用:

import yargs from 'yargs';

const argv = yargs
    .option('label', {
    alias: 'l',
    describe: 'Execute bot with these labels',
    demandOption: false,
    type: 'string',
    })
    .option('console', {
    alias: 'c',
    describe: 'Log to console',
    demandOption: false,
    type: 'boolean',
    })
    .help()
    .alias('help', 'h')
    .argv;

if(argv.label){
    console.log('label')
}
Run Code Online (Sandbox Code Playgroud)

编译器抛出并错误:

Property 'label' does not exist on type '{ [x: string]: unknown; label: string | undefined; console: boolean | undefined; _: (string | number)[]; $0: string; } | Promise<{ [x: string]: unknown; label: string | undefined; console: boolean | undefined; _: (string | number)[]; $0: string; }>'.
  Property 'label' does not exist on type 'Promise<{ [x: string]: unknown; label: string | undefined; console: boolean | undefined; _: (string | number)[]; $0: string; }>'
Run Code Online (Sandbox Code Playgroud)

sha*_*awn 5

理论上,argv可能会返回一个承诺,这会使返回的类型变得复杂。

不要打电话argv,而是尝试打电话.parseSync()。然后 TypeScript 知道它正在处理什么并且label将成为预期的属性。