Property does not exist using yargs and typescript

616 Views Asked by At

I am trying to parse a command line with yargs in typescript and it doesn't work:

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')
}

The compiler throws and error:

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; }>'
1

There are 1 best solutions below

0
shadowspawn On

Theoretically, argv may return a promise which is complicating the returned type.

Instead of calling argv, try calling .parseSync() instead. Then TypeScript knows what it is working with and label will be an expected property.