DEV Community

Discussion on: Creating a CLI for your Node.js app using Typescript

Collapse
 
rulatir profile image
rulatir

Yargs sadly fails to support the super-common idiom of "subset of allowed values". Setting the "choices" array for an option breaks the "array" functionality: the value is still returned as array, but only contains the first element specified on the command line.

Collapse
 
int0h profile image
int0h

I tried to reproduce it. But yargs worked for me. Both app -o a -o b and app -o a b printed o: ['a', 'b']. The first approach also worked with typed-cli. Can you provide with a code sample of what you mean exactly?

Collapse
 
rulatir profile image
rulatir • Edited

Turns out it was not choices that was the culprit but requiresArg. It's an embarrasing, long-standing bug in yargs. I made a PR to revert the commit that introduced it.

Collapse
 
quaos profile image
QuaOs

I got TypeError using choices with array in latest version 17.6.2

const parsedArgs: MyArgs = await yargs(process.argv.slice(2))
  // ...
  .options({
    statuses: {
      type: 'array',
      array: true,
      choices: Object.values(MyStatusEnum),
    },
    // ...
  })
}).argv

^^^^
Type '{ [x: string]: unknown; statuses: MyStatusEnum; ... 5 more ...; $0: string; } | { ...; }'
 is not assignable to type 'MyArgs'.
Enter fullscreen mode Exit fullscreen mode