tj/commander.js · error · InvalidArgumentError

Allowed choices are ${this.argChoices.join(', ')}.

Error message

Allowed choices are ${this.argChoices.join(', ')}.

What it means

Thrown at parse time (not construction time) when an Option configured with .choices(values) receives a command-line argument that is not in the allowed list. The choices() method replaces the option's parseArg with a validator that throws InvalidArgumentError, which extends CommanderError with exitCode 1 and code 'commander.invalidArgument'. Commander normally catches this itself, prints the message (listing the allowed values), and exits with code 1; the message interpolates this.argChoices.join(', ').

Source

Thrown at lib/option.js:185

      return [value];
    }

    previous.push(value);
    return previous;
  }

  /**
   * Only allow option value to be one of choices.
   *
   * @param {string[]} values
   * @return {Option}
   */

  choices(values) {
    this.argChoices = values.slice();
    this.parseArg = (arg, previous) => {
      if (!this.argChoices.includes(arg)) {
        throw new InvalidArgumentError(
          `Allowed choices are ${this.argChoices.join(', ')}.`,
        );
      }
      if (this.variadic) {
        return this._collectValue(arg, previous);
      }
      return arg;
    };
    return this;
  }

  /**
   * Return option name.
   *
   * @return {string}
   */

  name() {

View on GitHub (pinned to ba6d13ddb4)

Solutions

  1. Pass one of the allowed values on the command line.
  2. Extend the choices array to include the missing value: .choices(['red','green','blue']).
  3. If case-insensitivity is intended, normalize via .argParser before choices, or add both cases to choices.
  4. Give the option a sensible default so the flag can be omitted, or make it optional ([value]) so an invalid value can be avoided.
  5. Document the allowed values in the option description so users see them in --help.

Example fix

// before
program.addOption(new Option('--color <c>').choices(['red', 'green']));
// $ cli --color blue  =>  error: Allowed choices are red, green.

// after (extend choices)
program.addOption(new Option('--color <c>').choices(['red', 'green', 'blue']));
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-scan argv against declared choices so you control the message.
function validateChoices(optionName, allowed, rawValue) {
  if (rawValue !== undefined && !allowed.includes(rawValue)) {
    throw new Error(
      `Invalid value '${rawValue}' for ${optionName}. Allowed: ${allowed.join(', ')}`
    );
  }
}
// usage before parse:
// validateChoices('--color', ['red', 'green'], process.env.COLOR);

Type guard

function isAllowedChoice(value, choices) {
  return Array.isArray(choices) && choices.includes(value);
}

Try / catch

// Commander catches InvalidArgumentError itself and exits 1. To intercept it,
// install exitOverride and catch around parse.
const { Command, InvalidArgumentError } = require('commander');
const program = new Command();
program.exitOverride(); // re-throw instead of process.exit
try {
  program.parseAsync(process.argv); // or parse()
} catch (err) {
  if (err instanceof InvalidArgumentError || err.code === 'commander.invalidArgument') {
    console.error(`Bad input: ${err.message}`);
    process.exit(err.exitCode ?? 1);
  }
  throw err;
}

Prevention

When it happens

Trigger: Defining new Option('--color <c>').choices(['red','green']) (or .option('--color <c>').choices(...)) and the end user running `cli --color blue`. Also triggered by variadic choice options when any one supplied value is outside the list, and by options whose value comes from a preset/env var that was not added to the choices.

Common situations: End-user typos on enum-style options; a new valid value added to the product but not to the choices array; case sensitivity ('Red' vs 'red') because the check is a strict includes(); env var or default values that fall outside the declared choices.

Related errors


AI-assisted analysis of tj/commander.js@ba6d13ddb4 (2026-08-03). Data as JSON: /data/errors/e636a2d830641387.json. Report an issue: GitHub.