From 6ae0c3f59d6ba9f6f071521827ae9e5801ef5736 Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Sun, 8 Nov 2026 16:14:27 +0530 Subject: [PATCH] fix: ignore the configured default for an option with zero narg An option configured with `narg: 0` takes no arguments, so passing it is a switch and its value should be the one implied by its type. `eatNargs` instead called `defaultValue`, which returns the configured `default` for any option not declared `boolean` or `count`, so a `default` of `false` made the option parse as `false` even when it was given: parser(['-b'], { narg: { b: 0 }, default: { b: false } }) // => { b: false }, expected { b: true } Use the type's value directly. The configured default still applies when the option is absent. Fixes #418 --- lib/yargs-parser.ts | 5 ++++- test/yargs-parser.mjs | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/yargs-parser.ts b/lib/yargs-parser.ts index 13a70d12..a9783df5 100644 --- a/lib/yargs-parser.ts +++ b/lib/yargs-parser.ts @@ -536,7 +536,10 @@ export class YargsParser { if (!isUndefined(argAfterEqualSign)) { error = Error(__('Argument unexpected for: %s', key)); } - setArg(key, defaultValue(key)); + // An option configured to take no arguments is a switch, so its value + // is the one implied by its type. The configured default applies when + // the option is absent, not when it is given without a value. + setArg(key, defaultForType(guessType(key))); return i; } diff --git a/test/yargs-parser.mjs b/test/yargs-parser.mjs index 91c042a0..3b23d9f7 100644 --- a/test/yargs-parser.mjs +++ b/test/yargs-parser.mjs @@ -307,6 +307,27 @@ describe('yargs-parser', function () { parse.should.have.property('_').and.deep.equal(['false', 7, 'foo']); }); + it('should not use the configured default for an option given with zero narg', function () { + const parse = parser(['-a', 'hello', '-b', 'world'], { + narg: {a: 1, b: 0}, + default: {b: false}, + alias: {blah: ['b', 'bl']}, + }); + parse.should.have.property('a', 'hello'); + parse.should.have.property('b', true).and.be.a('boolean'); + parse.should.have.property('blah', true).and.be.a('boolean'); + parse.should.have.property('bl', true).and.be.a('boolean'); + parse.should.have.property('_').and.deep.equal(['world']); + }); + + it('should use the configured default for an option with zero narg that is not given', function () { + const parse = parser([], { + narg: {b: 0}, + default: {b: false}, + }); + parse.should.have.property('b', false).and.be.a('boolean'); + }); + it('should allow defining options as boolean in groups', function () { const parse = parser(['-x', '-z', 'one', 'two', 'three'], { boolean: ['x', 'y', 'z'],