Skip to Content
Course content

76: Building a Typed CLI Tool

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You might be tempted to think that since process.argv is already typed as string[] in Node.js, your CLI tool is "typed" the moment you start reading arguments. It feels like the work is already done for you.

Here is why that is a dangerous trap. Let's say you're building a tool to optimize images, and you expect a --quality flag. If you just grab the value from the array, you aren't actually working with a number; you're working with a string that looks like a number. If you use a type assertion like as number to force it, you're lying to the TypeScript compiler. The compiler will stop complaining, but your code will crash the second you try to perform a mathematical operation on that value at runtime.

The "process.argv is enough" fallacy

// This looks fine to TS, but it's a runtime disaster waiting to happen
const args = process.argv.slice(2);
const quality = args[1] as unknown as number; 

// If the user passes "--quality 80", quality is actually the string "80"
// This will result in "8080" instead of 160
console.log(quality + 80); 

In the example above, TypeScript is happy because we forced the type, but the reality of the CLI environment is that everything entering your program is a string. A truly typed CLI tool isn't about how you cast the input, but how you parse and validate it into a known schema before it ever hits your business logic.

Bridging the gap between raw strings and domain types

To do this right, you need a boundary layer. I usually reach for a library like commander or yargs, but the secret sauce is defining a strict interface for your parsed options and ensuring the parser actually adheres to it. You want to move from string[] to a Config object as early as possible.

Let's look at how I'd actually structure the image optimizer tool. I want a specific set of formats and a guaranteed number for quality.

import { program } from 'commander';

type ImageFormat = 'webp' | 'jpg' | 'png';

interface CliOptions {
  source: string;
  quality: number;
  format: ImageFormat;
}

program
  .requiredOption('-s, --source ', 'path to source image')
  .option('-q, --quality ', 'compression quality (1-100)', (val) => parseInt(val, 10))
  .option('-f, --format ', 'output format (webp, jpg, png)', 'webp')
  .parse(process.argv);

// We cast the options once at the boundary. 
// Because we used a parsing function for 'quality', it's actually a number now.
const options = program.opts() as unknown as CliOptions;

if (options.quality < 1 || options.quality > 100) {
  console.error('Error: Quality must be between 1 and 100');
  process.exit(1);
}

console.log(`Optimizing ${options.source} to ${options.format} at ${options.quality}%`);

Notice what happened here. I didn't just tell TypeScript "trust me, this is a number." I used the commander custom processing function (val) => parseInt(val, 10) to actually change the data type at runtime. The interface CliOptions then acts as the contract for the rest of my application. Now, if I try to pass options.quality into a function that expects a string, TypeScript will actually catch it—which is exactly what we want.

I've found that treating CLI input as "untrusted" until it passes through a validation layer saves me hours of debugging "undefined is not a function" errors that only happen when a user forgets a flag in production.




📋 Practical Task

Build a Typed Log-Filtering CLI

Create a CLI tool called log-filter that reads a log file and filters entries by a specific severity level. Your tool must implement the following requirements:

  • Define a union type Severity = 'INFO' | 'WARN' | 'ERROR'.
  • Define a FilterOptions interface that includes filePath (string) and level (Severity).
  • Use a CLI parser (like commander) to handle the arguments.
  • Implement a custom parsing function for the level argument that converts the user's input to uppercase and validates that it is one of the three allowed Severity values. If the value is invalid, the program should print an error and exit.
  • Ensure that once the options are parsed, the rest of your logic interacts only with the typed FilterOptions object, not the raw process.argv.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.