or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arguments.mdcommands.mderrors.mdhelp.mdindex.mdoptions.md
tile.json

options.mddocs/

Options Management

Comprehensive option system supporting boolean options, value options, variadic options, required options, option validation, conflicts, environment variable integration, and extensive configuration capabilities.

Capabilities

Option Factory Function

Create new Option instances programmatically.

/**
 * Creates a new Option instance
 * @param flags - Option flags specification (e.g., '-p, --port <number>')
 * @param description - Option description
 * @returns New Option instance
 */
function createOption(flags: string, description?: string): Option;

Usage Examples:

import { createOption } from 'commander';

const portOption = createOption('-p, --port <number>', 'server port number')
  .default(3000)
  .env('PORT');

const verboseOption = createOption('-v, --verbose', 'verbose output');

Option Class

Represents a command-line option with flags, processing, and validation.

/**
 * Represents a command-line option with flags and processing
 */
class Option {
  /**
   * Initialize an option with flags and description
   * @param flags - Option flags (e.g., '-p, --port <number>')
   * @param description - Option description
   */
  constructor(flags: string, description?: string);
  
  // Properties
  flags: string;
  description: string;
  required: boolean;
  optional: boolean;
  variadic: boolean;
  mandatory: boolean;
  short?: string;
  long?: string;
  negate: boolean;
  defaultValue?: any;
  defaultValueDescription?: string;
  presetArg?: unknown;
  envVar?: string;
  parseArg?: Function;
  hidden: boolean;
  argChoices?: string[];
  conflictsWith: string[];
  implied?: object;
  helpGroupHeading?: string;
}

Command Option Management

Add and configure options on commands.

interface Command {
  /**
   * Define an option
   * @param flags - Option flags
   * @param description - Option description
   * @param defaultValue - Default value
   * @returns this command for chaining
   */
  option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
  
  /**
   * Define an option with custom parser
   * @param flags - Option flags
   * @param description - Option description
   * @param parseArg - Custom parsing function
   * @param defaultValue - Default value
   * @returns this command for chaining
   */
  option<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;
  
  /**
   * Define a required option
   * @param flags - Option flags
   * @param description - Option description
   * @param defaultValue - Default value
   * @returns this command for chaining
   */
  requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
  
  /**
   * Add a prepared Option instance
   * @param option - Option instance to add
   * @returns this command for chaining
   */
  addOption(option: Option): this;
  
  /**
   * Factory for creating Option instances (can be overridden)
   * @param flags - Option flags
   * @param description - Option description
   * @returns New Option instance
   */
  createOption(flags: string, description?: string): Option;
}

Usage Examples:

program
  // Boolean option
  .option('-v, --verbose', 'verbose output')
  
  // Value option
  .option('-p, --port <number>', 'server port number')
  
  // Optional value option
  .option('-c, --config [file]', 'configuration file')
  
  // Option with default value
  .option('-h, --host <host>', 'server host', 'localhost')
  
  // Required option
  .requiredOption('-k, --key <key>', 'API key')
  
  // Option with custom parser
  .option('-n, --number <value>', 'a number', parseInt)
  
  // Variadic option
  .option('-f, --files <files...>', 'input files');

Option Configuration

Configure option behavior, validation, and processing.

interface Option {
  /**
   * Set default value and optional description
   * @param value - Default value
   * @param description - Description of default value
   * @returns this option for chaining
   */
  default(value: unknown, description?: string): this;
  
  /**
   * Set preset value for when option is used without argument
   * @param arg - Preset value
   * @returns this option for chaining
   */
  preset(arg: unknown): this;
  
  /**
   * Set conflicting options
   * @param names - Option names that conflict with this one
   * @returns this option for chaining
   */
  conflicts(names: string | string[]): this;
  
  /**
   * Set implied option values
   * @param optionValues - Option values to set when this option is used
   * @returns this option for chaining
   */
  implies(optionValues: OptionValues): this;
  
  /**
   * Set environment variable to check for option value
   * @param name - Environment variable name
   * @returns this option for chaining
   */
  env(name: string): this;
  
  /**
   * Set custom argument parser
   * @param fn - Parsing function
   * @returns this option for chaining
   */
  argParser<T>(fn: (value: string, previous: T) => T): this;
  
  /**
   * Make option mandatory (must have value after parsing)
   * @param mandatory - Whether option is mandatory
   * @returns this option for chaining
   */
  makeOptionMandatory(mandatory?: boolean): this;
  
  /**
   * Hide option from help display
   * @param hide - Whether to hide option
   * @returns this option for chaining
   */
  hideHelp(hide?: boolean): this;
  
  /**
   * Restrict option value to specific choices
   * @param values - Allowed values
   * @returns this option for chaining
   */
  choices(values: readonly string[]): this;
  
  /**
   * Set help group heading
   * @param heading - Group heading for help display
   * @returns this option for chaining
   */
  helpGroup(heading: string): this;
}

Usage Examples:

import { createOption } from 'commander';

// Option with default value and description
const portOption = createOption('-p, --port <number>', 'server port')
  .default(3000, 'default port')
  .env('PORT');

// Option with choices restriction
const logLevelOption = createOption('-l, --log-level <level>', 'logging level')
  .choices(['error', 'warn', 'info', 'debug'])
  .default('info');

// Option with conflicts
const formatOption = createOption('--json', 'output as JSON')
  .conflicts(['xml', 'yaml']);

// Option with implications
const traceOption = createOption('--trace', 'enable tracing')
  .implies({ verbose: true, logLevel: 'debug' });

// Option with custom parser
const sizeOption = createOption('-s, --size <size>', 'file size')
  .argParser((value, previous) => {
    const size = parseInt(value);
    if (isNaN(size)) throw new InvalidArgumentError('Size must be a number');
    return size;
  });

// Hidden option
const debugOption = createOption('--debug-internal', 'internal debugging')
  .hideHelp();

Option Value Management

Access and manage option values on commands.

interface Command {
  /**
   * Get parsed option values as object
   * @returns Object containing option values
   */
  opts<T extends OptionValues>(): T;
  
  /**
   * Get option values including global options
   * @returns Object containing all option values
   */
  optsWithGlobals<T extends OptionValues>(): T;
  
  /**
   * Get specific option value
   * @param key - Option key
   * @returns Option value
   */
  getOptionValue(key: string): any;
  
  /**
   * Set option value
   * @param key - Option key
   * @param value - Option value
   * @returns this command for chaining
   */
  setOptionValue(key: string, value: unknown): this;
  
  /**
   * Set option value with source tracking
   * @param key - Option key
   * @param value - Option value
   * @param source - Value source
   * @returns this command for chaining
   */
  setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;
  
  /**
   * Get source of option value
   * @param key - Option key
   * @returns Value source
   */
  getOptionValueSource(key: string): OptionValueSource | undefined;
  
  /**
   * Get option value source including global options
   * @param key - Option key
   * @returns Value source
   */
  getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
}

Usage Examples:

program
  .option('-p, --port <number>', 'server port', '3000')
  .option('-v, --verbose', 'verbose output')
  .action(() => {
    const options = program.opts();
    console.log('Port:', options.port);
    console.log('Verbose:', options.verbose);
    
    // Check option source
    const portSource = program.getOptionValueSource('port');
    console.log('Port source:', portSource); // 'default', 'cli', 'env', etc.
  });

Option Utility Methods

Utility methods for option inspection and management.

interface Option {
  /**
   * Get option name (without dashes)
   * @returns Option name
   */
  name(): string;
  
  /**
   * Get camelCase attribute name for object keys
   * @returns Camelcase attribute name
   */
  attributeName(): string;
  
  /**
   * Check if argument matches this option
   * @param arg - Command line argument
   * @returns Whether argument matches this option
   */
  is(arg: string): boolean;
  
  /**
   * Check if option is boolean type
   * @returns Whether option is boolean
   */
  isBoolean(): boolean;
}

Usage Examples:

const option = createOption('-p, --port <number>', 'server port');

console.log(option.name());          // 'port'
console.log(option.attributeName()); // 'port'
console.log(option.is('--port'));    // true
console.log(option.is('-p'));        // true
console.log(option.isBoolean());     // false

const boolOption = createOption('-v, --verbose', 'verbose output');
console.log(boolOption.isBoolean()); // true

Option Types and Patterns

Different option flag patterns and their behaviors.

Boolean Options:

// Simple boolean flag
.option('-v, --verbose', 'verbose output')

// Negatable boolean
.option('--no-colors', 'disable colors')

Value Options:

// Required value
.option('-p, --port <number>', 'server port')

// Optional value
.option('-c, --config [file]', 'config file')

// Variadic (multiple values)
.option('-f, --files <files...>', 'input files')

Advanced Flag Patterns:

// Multiple long flags (for shorter alternatives)
.option('--ws, --workspace <name>', 'workspace name')

// Environment variable integration
.option('-p, --port <number>', 'port number')
  .env('PORT')

// Complex validation
.option('--size <n>', 'size in bytes')
  .argParser((value) => {
    const num = parseInt(value);
    if (num < 0) throw new InvalidArgumentError('Size must be positive');
    return num;
  })

Types

type OptionValues = Record<string, any>;

type OptionValueSource = 
  | 'default'     // From option.default()
  | 'config'      // From configuration file
  | 'env'         // From environment variable
  | 'cli'         // From command line
  | 'implied'     // From option.implies()
  | string        // Custom source
  | undefined;    // No source/unset