Sub topic 5
Validating Input at the Boundary
This chapter assumes you know basic TypeScript, including functions, types, and async/await. You should also be comfortable running Node.js commands from a terminal and reading a basic package.json.
A command-line program receives untrusted input from the shell. Users can omit arguments, provide too many files, misspell flags, or pass an option where a file name is expected. Validate this input at the program boundary, before the rest of the application uses it.
Separate Parsing from Validation
Parsing converts raw strings into structured values. Validation checks whether those values make sense for your command.
For example:
--lines report.txthas a valid flag and one positional argument.report.txt extra.txthas too many files for a command that accepts one file.--unknown report.txtcontains an unsupported option.- No arguments means the required file is missing.
node:util provides parseArgs for the first part. Its strict mode rejects unknown options and malformed option syntax. Your code must still validate the command's rules.
flowchart TD
A["Raw process.argv"] --> B["parseArgs"]
B --> C{"Syntax valid?"}
C -->|No| D["Show usage and return exit code 2"]
C -->|Yes| E{"Exactly one file?"}
E -->|No| D
E -->|Yes| F["Create typed command"]
F --> G["Read the file"]Return a Typed Command
A discriminated union is a type whose members share a field, such as kind, but have different values and fields. It lets TypeScript connect a command's kind to the data that belongs to it.
The following parser accepts -l or --lines, -h or --help, and exactly one file name.
import { parseArgs } from "node:util";
type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };
function parseCommand(argv: string[]): Command {
let parsed;
try {
parsed = parseArgs({
args: argv,
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
strict: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`invalid arguments: ${message}`);
}
if (parsed.values.help === true) {
return { kind: "help" };
}
if (parsed.positionals.length !== 1) {
throw new Error("expected exactly one file");
}
return {
kind: "count",
file: parsed.positionals[0]!,
linesOnly: parsed.values.lines === true,
};
}
function usage(): void {
console.log("usage: wcl [-l] <file>");
}
function main(argv: string[]): number {
try {
const command = parseCommand(argv);
if (command.kind === "help") {
usage();
return 0;
}
console.log(
`file=${command.file}, linesOnly=${command.linesOnly}`,
);
return 0;
} catch (error) {
console.error(`wcl: ${error instanceof Error ? error.message : error}`);
usage();
return 2;
}
}
process.exitCode = main(process.argv.slice(2));The ! after parsed.positionals[0] tells TypeScript that the value exists. The length check immediately above proves this at runtime. Without that check, an empty positional list could produce undefined.
Choose Validation Errors Carefully
Use exit code 2 for invalid command-line input. This convention distinguishes a usage error from a failure while processing a valid command.
Validation should also have a clear scope:
parseArgschecks option syntax and supported flags.parseCommandchecks the number and role of arguments.- File-reading code checks whether the path exists and can be opened.
- Counting logic processes already-read text.
This separation keeps each function focused and makes later tests easier to write.
Exercise
What should parseCommand(["--lines"]) do, and why should it fail before attempting file I/O?
Show answer
It should throw an argument-validation error because the required file positional argument is missing. No file operation should run for an invalid command.