Command-Line Calculator
Command-Line Calculator — purpose and prerequisites
A command-line calculator receives an operation and operands, validates them, and prints a result or clear error. This first version calls the calculation function directly so it runs unchanged in any Node environment; the companion CLI reads process.argv for actual commands.
What you’ll learn
- Explain the purpose of command-line calculator.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
A union restricts the supported operators. The switch performs each operation and rejects division by zero. The project extension parses operands from argv and reports invalid commands.
Converting an invalid operand with Number may yield NaN; validate with Number.isFinite before calculating.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
type Operator = "+" | "-" | "*" | "/";
function calculate(a: number, operator: Operator, b: number): number {
if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error("Invalid number");
switch (operator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": if (b === 0) throw new Error("Division by zero"); return a / b;
}
}
console.log(calculate(12, "+", 8));
console.log(calculate(12, "/", 4));Verified output
20
3Compile: npx tsc --strict --target es2022 --module commonjs command-line-calculator.ts; run: node command-line-calculator.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
A union restricts the supported operators. The switch performs each operation and rejects division by zero. The project extension parses operands from argv and reports invalid commands.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Build the practical integration
Integration companion: The primary example above is self-contained. The files below demonstrate a real framework, runtime, or project setup and may need additional packages or a browser.
cli.ts
const [, , left, operator, right] = process.argv;
const a = Number(left), b = Number(right);
if (left === undefined || right === undefined || !["+", "-", "*", "/"].includes(operator ?? "") || !Number.isFinite(a) || !Number.isFinite(b) || (operator === "/" && b === 0)) {
console.error("Usage: node cli.js <number> <+|-|*|/> <number>");
process.exitCode = 1;
} else {
const result = operator === "+" ? a+b : operator === "-" ? a-b : operator === "*" ? a*b : a/b;
console.log(result);
}Setup and execution
npm i -D typescript @types/node
npx tsc --strict --target es2022 --module commonjs cli.ts
node cli.js 12 + 8Unlike the primary function-only example, this additional program really reads command-line arguments from process.argv.
Validation: This companion’s TypeScript source was also compiled successfully. Network-facing or browser interaction was not runtime-tested.
Common mistake and correction
Converting an invalid operand with Number may yield NaN; validate with Number.isFinite before calculating.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Implement src/cli.ts that reads argv.slice(2), validates the operator and arguments, and sets a nonzero exit code for errors.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
A union restricts the supported operators. The switch performs each operation and rejects division by zero. The project extension parses operands from argv and reports invalid commands.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.