Sub topic 6
Modeling Commands with Types
Assume you know basic TypeScript types, functions, async/await, and how node:util parseArgs produces option values and positional arguments. This chapter focuses on turning that loosely shaped input into a small, safe command model.
A command-line parser usually gives you general data:
- Boolean options such as
helpandlines. - An array of positional arguments.
- Values that may be missing or appear in an unexpected combination.
Your application should validate this data at its boundary. After validation, the rest of the program should work with a precise type.
Use a discriminated union
A discriminated union is a type made from several object types that share one identifying property. Here, the shared property is kind.
type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };The kind property is the discriminator. TypeScript uses its value to determine which other properties are available.
A help command has no file property. A count command always has a file and a linesOnly setting. This prevents invalid combinations such as a command that is both help and count.
function describe(command: Command): string {
switch (command.kind) {
case "help":
return "usage: wcl [-l] <file>";
case "count":
return `counting ${command.file}${
command.linesOnly ? " (lines only)" : ""
}`;
}
}
console.log(describe({ kind: "help" }));
console.log(describe({ kind: "count", file: "notes.txt", linesOnly: true }));Inside the "count" case, TypeScript knows that command.file and command.linesOnly exist. This behavior is called narrowing. The compiler narrows the union after checking the discriminator.
Validate raw input once
Keep parser-specific details at the edge of the program. Convert them into a Command before calling application logic.
type RawValues = {
help?: boolean;
lines?: boolean;
};
function parseCommand(
values: RawValues,
positionals: string[],
): Command {
if (values.help) {
if (values.lines || positionals.length > 0) {
throw new Error("--help cannot be combined with other arguments");
}
return { kind: "help" };
}
if (positionals.length !== 1) {
throw new Error("expected exactly one file");
}
return {
kind: "count",
file: positionals[0],
linesOnly: values.lines ?? false,
};
}
const command = parseCommand(
{ lines: true },
["notes.txt"],
);
console.log(describe(command));The ?? operator supplies false only when values.lines is undefined or null. It does not replace another meaningful value.
Validation rules belong here because this function is the boundary between untrusted user input and the typed application. Later functions no longer need to repeatedly check whether a file exists in the argument list.
Make handling exhaustive
As the tool grows, you may add commands such as version. An exhaustive switch makes forgotten cases visible during compilation.
function run(command: Command): number {
switch (command.kind) {
case "help":
console.log("usage: wcl [-l] <file>");
return 0;
case "count":
console.log(`would count ${command.file}`);
return 0;
default: {
const unreachable: never = command;
return unreachable;
}
}
}The never type represents a value that should be impossible. If you add another member to Command but forget to add a case, the assignment to unreachable fails. The compiler therefore points to the missing behavior.
Follow the data flow
This structure keeps parsing, validation, and command behavior distinct. Each part has one reason to change, and the compiler helps keep the parts aligned.
Exercise
What property should you add to a new command variant so TypeScript can narrow it in a switch?
Show answer
Add a shared discriminator such as kind, with a unique string literal value for that variant.