Sub topic 6
Modeling commands with types
What this chapter assumes
This chapter assumes you have the wcl project from the earlier chapters: a TypeScript project in ESM mode with strict enabled, and an entry point that reads process.argv through util.parseArgs. You should be comfortable with union types and switch statements. Everything here is plain TypeScript, so no new packages are needed.
By the end you will be able to:
- Replace a loose options object with a discriminated union.
- Convert parsed arguments into a
Commandin one function. - Make the compiler report any command you forgot to handle.
- Avoid the common ways these types stop protecting you.
The problem with a bag of optional fields
parseArgs returns values, an object where each flag is boolean | undefined, and positionals, an array of strings. The obvious next step is to pass these around as they are, or to copy them into an options interface:
interface Options {
help?: boolean;
lines?: boolean;
file?: string;
}This type allows combinations that make no sense. { help: true, file: "a.txt" } is valid, and so is {}. Every function that receives an Options must re-check which combination it got. For example, file might be missing and the code has to decide whether that is an error or a request for help. Those checks get scattered through the program and drift apart over time.
A better approach is to decide once, at the boundary, what the user asked for. After that point the rest of the program works with a value that can only be one of a few valid shapes.
A discriminated union
A discriminated union is a union of object types that share one property with a literal type, called the discriminant. In wcl the discriminant is kind:
export type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };Each variant carries only the fields that make sense for it. A help command has no file. A count command always has a file, and it is a string, not string | undefined.
When you check the discriminant, TypeScript narrows the type inside that branch:
function describe(cmd: Command): string {
if (cmd.kind === "help") {
return "usage: wcl [-l] <file>";
}
// cmd is narrowed to the count variant here
return `counting ${cmd.file}${cmd.linesOnly ? " (lines only)" : ""}`;
}Accessing cmd.file before the check is a compile error, because help has no such property. The compiler enforces the rule that you only read a field after confirming the variant that owns it.
Two details are easy to miss:
- The discriminant must be a literal type such as
"help". A plainstringfield does not narrow anything. - The names of the fields are part of your design.
linesOnlysays what the flag does for the program, whilelinesonly repeats the flag's spelling. Prefer names that describe behavior.
Exhaustiveness checking with never
Adding a variant later is where this design pays off. Handle commands in a switch and add a default branch that assigns the value to a variable of type never:
export function describe(cmd: Command): string {
switch (cmd.kind) {
case "help":
return "usage: wcl [-l] <file>";
case "count":
return `counting ${cmd.file}${cmd.linesOnly ? " (lines only)" : ""}`;
default: {
const unreachable: never = cmd;
return unreachable;
}
}
}After the help and count cases, TypeScript has narrowed cmd to never, which means no possible value remains. The assignment compiles. Now add a third variant:
export type Command =
| { kind: "help" }
| { kind: "version" }
| { kind: "count"; file: string; linesOnly: boolean };Without touching describe, the compiler reports an error on the never assignment: Type '{ kind: "version"; }' is not assignable to type 'never'. The error appears at every switch that lacks a version case. That makes the type a to-do list for you.
If you use this pattern in several places, move it into a helper:
export function assertNever(value: never): never {
throw new Error(`Unhandled command: ${JSON.stringify(value)}`);
}The helper has two jobs. At compile time, its never parameter produces the same error as above. At run time, it throws if a value somehow slips through, for example from a cast or from untyped data. The runtime throw matters because types are erased when TypeScript compiles to JavaScript, so the compiler's guarantee only holds for code it can see.
Turning parsed arguments into a Command
Now connect the union to parseArgs. A single function takes the raw argument list and returns either a Command or an error message. Returning a result, rather than throwing, makes failure part of the type. This is another discriminated union, with ok as the discriminant:
import { parseArgs } from "node:util";
export type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };
export type ParseResult =
| { ok: true; command: Command }
| { ok: false; message: string };
export function parseCommand(argv: string[]): ParseResult {
try {
const { values, positionals } = parseArgs({
args: argv,
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
});
if (values.help) {
return { ok: true, command: { kind: "help" } };
}
const [file, ...extra] = positionals;
if (file === undefined) {
return { ok: false, message: "missing file argument" };
}
if (extra.length > 0) {
return { ok: false, message: `expected one file, got ${positionals.length}` };
}
return {
ok: true,
command: { kind: "count", file, linesOnly: values.lines ?? false },
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { ok: false, message };
}
}Several choices here are worth noting.
- Flag priority is explicit. If
--helpis present, the function returnshelpand ignores everything else. The rule lives in one place, and you can change it without searching the program. - Defaults are resolved here.
values.linesisboolean | undefined. The expressionvalues.lines ?? falseturns it into a plainbooleanbefore it enters theCommand, so no later code deals withundefined. - The
tryblock covers the call toparseArgs. By defaultparseArgsis strict and throws aTypeErroron an unknown flag such as--bogus. Thecatchturns that into a normal error result with the library's message. - The function is pure. It takes an array and returns a value, with no reads from
process, no output, and no exit. That makes it easy to test, which a later chapter does.
The caller then uses the narrowed result:
const result = parseCommand(process.argv.slice(2));
if (!result.ok) {
console.error(`wcl: ${result.message}`);
process.exitCode = 2;
} else {
console.log(describe(result.command));
}Inside the else branch, result.command exists. Inside the if branch, only result.message exists. Mixing them up is a compile error.
Where the types stop protecting you
The union only helps if values really have the declared shape. These are the usual ways it breaks.
| Mistake | What happens | Fix |
|---|---|---|
| `const cmd = { kind: "help" }` passed to a function expecting `Command` | TypeScript infers `kind: string`, so the call fails to compile | Annotate the variable: `const cmd: Command = { kind: "help" }` |
| Casting with `as Command` on parsed data | The compiler trusts you, and a wrong shape reaches the handler at run time | Build the value in `parseCommand`, never cast it |
| A `switch` with no `default` | New variants are silently ignored | Add the `never` assignment or call `assertNever` |
| Optional fields in a variant, such as `file?: string` | Brings back the "is it there?" checks the union was meant to remove | Make fields required, or split into another variant |
| Different handling of the same flag in two files | Behavior diverges over time | Keep all flag interpretation in `parseCommand` |
| Using `if (values.lines)` as a fallback for missing values | Hides the difference between `false` and `undefined` | Use `??` and decide the default once |
Remember too that positionals is a string[]. With the default compiler settings, positionals[0] is typed as string even when the array is empty. Destructuring and then comparing with undefined, as parseCommand does, is correct either way. If you want the compiler to enforce this, add "noUncheckedIndexedAccess": true to tsconfig.json. That setting makes every array index read T | undefined.
Extending the model
Suppose you want a --words flag that counts only words. Work through the change in this order:
- Add
words: { type: "boolean", short: "w" }to theparseArgsoptions. - Decide how
--linesand--wordsinteract. One option is to replacelinesOnly: booleanwithmode: "lines" | "words" | "both". A string literal union is clearer than two booleans that can contradict each other. - Update
parseCommandto computemode, and return an error result if both flags are given when you decide that combination is invalid. - Fix the compile errors in each
switch, because the type has changed and the compiler lists every place that needs an update.
Step 2 is the same idea as the discriminated union applied to a single field. When two flags cannot be combined, represent that in the type instead of checking for it in several places.
Exercise
You add a { kind: "version" } variant to Command, but you only update parseCommand. The project still compiles with no errors, and wcl --version crashes at run time with an unhandled case. What is most likely missing from the code that handles commands, and what should it contain?
Show answer
The switch over cmd.kind has no exhaustiveness check. Add a default branch that assigns cmd to a variable of type never, or passes it to an assertNever(value: never) helper. With that in place the compiler reports an error at the switch as soon as version is added to the union. The never check also needs strict to be enabled.
Exercise
Write the extra parseCommand branch needed so that wcl --lines --words file.txt is rejected with an error result, assuming values.lines and values.words are both boolean | undefined.
Show answer
Place this after the help check and before building the count command:
if (values.lines && values.words) {
return { ok: false, message: "--lines and --words cannot be combined" };
}
It returns the { ok: false, message } variant of ParseResult, so the caller prints the message to stderr and sets a non-zero exit code.