Course contentsShow
← JavaScript
Lesson 1515 of 2,72333. JavaScript in Node.jsFree lesson

Validating and Coercing Argument Types

Ensure command-line inputs match expected types and provide clear error messages on invalid input.

Validating and Coercing Argument Types

You'll learn how to ensure command-line arguments are the correct type and give users helpful feedback when they're not.

The Type Problem with CLI Arguments

When you grab arguments with process.argv or a parsing library like yargs, everything arrives as a string. If you expect a number, boolean, or other type, you need to convert (coerce) and validate it yourself—or you'll get unexpected bugs when "5" + 2 equals "52" instead of 7.

Think of it like a restaurant order form: if someone writes "three" instead of "3" for quantity, the kitchen needs to either convert it to a number or politely reject the order with a clear explanation.

Validation and Coercion Strategy

Type coercion transforms string inputs into the expected type. Validation checks whether the input is acceptable:

// Manual validation and coercion
const args = process.argv.slice(2);
const port = Number(args[0]);

if (isNaN(port)) {
  console.error('Error: Port must be a valid number');
  process.exit(1);
}

if (port < 1024 || port > 65535) {
  console.error('Error: Port must be between 1024 and 65535');
  process.exit(1);
}

console.log(`Starting server on port ${port}`);

With yargs, you can enforce types declaratively:

const argv = require('yargs')(process.argv.slice(2))
  .option('port', {
    type: 'number',
    demandOption: true,
    describe: 'Port to run server on'
  })
  .check(argv => {
    if (argv.port < 1024 || argv.port > 65535) {
      throw new Error('Port must be between 1024 and 65535');
    }
    return true;
  })
  .argv;

Good validation gives immediate, clear error messages so users know exactly what went wrong and how to fix it.

Key Takeaway: Always validate and coerce CLI arguments to match expected types, providing clear error messages with process.exit(1) on failure to prevent silent bugs and guide users toward correct usage.