yargs / yargs/yargs-parser

Setting an argument to both array and number gives unexpected results

Open
#135 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement help wanted
Dominant language
JavaScript
Stars
519
Forks
129
Avg merge
1h 34m
Merged PRs (30d)
1

Description

Calling this example code:

const yargsParser = require('yargs-parser');

const argv = yargsParser(process.argv.slice(2), {
	array: ['arr'],
});

console.log(JSON.stringify(argv, null, 2));

with these arguments:

node example.js --arr foo 2 bar

gives (as expected) the following output:

{
  "_": [],
  "arr": [
    "foo",
    2,
    "bar"
  ]
}

Adjusting the parsing options to treat the array as strings:

const yargsParser = require('yargs-parser');

const argv = yargsParser(process.argv.slice(2), {
	array: ['arr'],
	string: ['arr'],
});

console.log(JSON.stringify(argv, null, 2));

gives the following output (also as expected):

{
  "_": [],
  "arr": [
    "foo",
    "2",
    "bar"
  ]
}

However, if I tell it to treat the array as numbers:

const yargsParser = require('yargs-parser');

const argv = yargsParser(process.argv.slice(2), {
	array: ['arr'],
	number: ['arr'],
});

console.log(JSON.stringify(argv, null, 2));

then I would expect to get all array elements parsed as numbers:

{
  "_": [],
  "arr": [
    null,
    2,
    null
  ]
}

Instead, I get this result:

{
  "_": [],
  "arr": [
    null
  ]
}

Notably, this is also the case if all array elements are valid numbers:

node example.js --arr 1 2 3

gives the same result:

{
  "_": [],
  "arr": [
    null
  ]
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with the yargs-parser example and the --arr arguments shown in the report, comparing array, string, and number parsing. Trace the parser's handling of options that declare the same name as both array and number; done means every array element follows the expected numeric conversion behavior, including invalid values.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.