5 min read
|
Saved February 14, 2026
|
Copied!
Do you care about this?
The article argues against using if statements for validating command-line interface (CLI) flags, highlighting the limitations of traditional libraries. It introduces Optique, a TypeScript library that allows for modeling relationships between options directly in the parser, enabling better type safety and reducing the need for runtime checks.
If you do, here's more
The article critiques how traditional Command Line Interface (CLI) libraries handle option validation, particularly in TypeScript. It highlights the common practice of using if statements to check relationships between command-line flags, leading to repetitive and error-prone code. For example, the author points out that when using a "junit" or "html" reporter, the `--output-file` option is required, but should be ignored for the "console" reporter. The current TypeScript libraries like Commander and yargs fail to capture these relationships in their type systems, forcing developers to write additional runtime checks.
Modern libraries like cmd-ts and Clipanion improve type safety but still fall short in modeling the interdependencies of options. The author introduces Optique, a TypeScript library that uses a `conditional()` construct to manage option relationships. This allows the parser to infer types based on the selected reporter, ensuring that `outputFile` is treated as a string when "junit" or "html" is chosen, while remaining absent when "console" is selected. This approach eliminates the need for validation code and provides compile-time safety, reducing the risk of errors.
The article expands on this concept with a more complex example involving database connections, where different database types require distinct options. By modeling these relationships with `conditional()`, each database configuration can be accurately represented, preventing misuse of options that donβt apply. The author notes that this pattern can be applied across various scenarios in CLI tools, such as authentication methods and deployment targets, allowing for more robust and maintainable command-line interfaces.
Questions about this article
No questions yet.