Search code examples
yargs

yargs argv not working anymore after update to latest version


I had this code

const argv = yargs
    .option("applyChanges", {
        alias: "a",
        description: "Apply the changes",
        type: "boolean"
    })
    .help()
    .alias("help", "h").argv;

const options = {
    applyChanges: argv.applyChanges ? argv.applyChanges : false
};

to get argv.applyChanges boolean value. But after the latest update to yargs 17 I get an error on argv.applyChanges saying

property 'applyChanges' does not exist on type '{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; } | Promise<{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; }>'. Property 'applyChanges' does not exist on type 'Promise<{ [x: string]: unknown; applyChanges: boolean | undefined; _: (string | number)[]; $0: string; }>'.

I tried to use await but without success. What should I do? This code was working with the previous yargs version 16.x.x


Solution

  • The type of argv is a union. The first item is the arguments and the second one is a promise which resolves to those arguments.

    The reason it's a union is because in yargs you can have commands, and the handlers for those commands can be asynchronous. And so .argv would resolve after that command finishes.

    In the example, you aren't using any asynchronous commands, but yargs typing doesn't know that when you are just calling .argv or .parse.

    What you need to do is use parseSync which explicitally tells yargs you have no asynchronous commands (this will also throw errors if there are async commands).

    const argv = yargs
        .option("applyChanges", {
            alias: "a",
            description: "Apply the changes",
            type: "boolean"
        })
        .help()
        .alias("help", "h").parseSync();
    
    const options = {
        applyChanges: argv.applyChanges ? argv.applyChanges : false
    };