Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow positional of type array to handle trailing positionals #2409

Open
djohnson-aperture opened this issue May 3, 2024 · 1 comment
Open

Comments

@djohnson-aperture
Copy link

I have a script that I'd like to collect the args at the end of the command as under a key, and still get type safety. Currently this isn't possible, as yargs.positional doesn't allow array as a type. Here's what I've had to resort to:

yargs(hideBin(process.argv))
.scriptName('do-something')
.command<{
  first: string;
  second: string;
  requiredRest: (number | string)[];
}>(
  '$0 <first> <second> <requiredRest..>',
  false,
  function (yargs) {
    return yargs
      .positional('first', { type: 'string', demandOption: true })
      .positional('second', { type: 'string', demandOption: true })
      .positional('requiredRest', { demandOption: true });
  },
  function (argv) {
    console.log(argv.first);
    console.log(argv.second);
    console.log(argv.requiredRest);
  },
)
.help().argv;

This does function, however, it requires me to do extra work by overriding the generic type for .command. Ideally, the builder would determine the type, which allowing positional to take type array would solve this. I'm not sure if there's a reason this isn't allowed, other than an array positional anywhere other than the end of the command doesn't make sense.

@shadowspawn
Copy link
Member

The array property is separate from the type property. For your example:

.positional('requiredRest', { type: 'string', array: true, demandOption: true });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants