TypeScript · Lesson 107 of 120
Project: A CLI
Process.argv.
Staff want to use the library from a terminal. A small command line tool turns words into calls. Place, cancel, and list.

- From a terminal
- Words become calls
- place, cancel, list
cli.ts
Run takes the command line words. The first word picks the command. Place reads a customer, then SKU colon quantity pairs. Cancel takes an ID. List prints a summary of every order. Anything else shows the usage.
cli.tstypescript
import { placeOrder, orders } from "./service.js";
import { cancelOrder } from "./cancel.js";
import { summarise } from "./reports.js";
export function run(args: string[]): string {
const [command, ...rest] = args;
switch (command) {
case "place": {
const [customer, ...items] = rest;
const lines = items.map(i => ({ sku: i.split(":")[0], qty: Number(i.split(":")[1]) }));
const r = placeOrder({ customer, lines });
return r.ok ? `placed ${r.value.id}` : `error: ${r.error}`;
}
case "cancel": { const r = cancelOrder(Number(rest[0]), "customer request");
return r.ok ? `cancelled ${r.value.id}` : `error: ${r.error}`; }
case "list": return orders.all().map(o => JSON.stringify(summarise(o))).join("\n");
default: return "usage: place NAME SKU:QTY... | cancel ID | list";
}
}Using the CLI
In a terminal, we'd pass process dot argv. Here, we call run with a few example commands. Run it. Orders are placed, cancelled, and listed.
app.tstypescript
import { run } from "./cli.js";
const commands = [
["place", "Sam", "TRAIL-500:1", "HELMET-M:1"],
["place", "Priya", "LIGHTS:2"],
["cancel", "1042"],
["list"],
];
for (const args of commands) console.log(`> ${args.join(" ")}\n${run(args)}`);Output
> place Sam TRAIL-500:1 HELMET-M:1
placed 1042
> place Priya LIGHTS:2
error: not enough stock for LIGHTS
> cancel 1042
cancelled 1042
> list
{"id":1042,"customer":"Sam","status":"cancelled","total":889.5}Also uses types.ts
export type Status = "packing" | "shipped" | "delivered" | "cancelled";
export interface Product {
sku: string;
name: string;
price: number;
}
export interface OrderLine {
sku: string;
qty: number;
}
export interface Order {
id: number;
customer: string;
lines: OrderLine[];
status: Status;
}Also uses catalog.ts
import type { Product } from "./types.js";
export const PRODUCTS: Product[] = [
{ sku: "TRAIL-500", name: "Trail 500", price: 849.5 },
{ sku: "HELMET-M", name: "Helmet", price: 40 },
{ sku: "LIGHTS", name: "Lights", price: 25 },
];
export const STOCK: Record<string, number> = { "TRAIL-500": 2, "HELMET-M": 10, LIGHTS: 0 };
export function product(sku: string): Product | undefined {
return PRODUCTS.find(p => p.sku === sku);
}Also uses schema.ts
import { z } from "zod";
export const NewOrderSchema = z.object({
customer: z.string().min(1, "customer is required"),
lines: z.array(z.object({
sku: z.string(),
qty: z.number().int().positive("qty must be positive"),
})).min(1, "an order needs at least one line"),
});
export type NewOrder = z.infer<typeof NewOrderSchema>;Also uses store.ts
export class Repository<T extends { id: number }> {
private items = new Map<number, T>();
save(item: T): T {
this.items.set(item.id, item);
return item;
}
find(id: number): T | undefined {
return this.items.get(id);
}
all(): T[] {
return [...this.items.values()];
}
}Also uses result.ts
export type Result<T> = { ok: true; value: T } | { ok: false; error: string };
export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
export const fail = <T = never>(error: string): Result<T> => ({ ok: false, error });Also uses events.ts
import type { Order } from "./types.js";
type Events = {
"order.placed": Order;
"order.cancelled": { id: number; reason: string };
};
type Listener<K extends keyof Events> = (payload: Events[K]) => void;
const listeners: { [K in keyof Events]: Listener<K>[] } = { "order.placed": [], "order.cancelled": [] };
export function on<K extends keyof Events>(name: K, fn: Listener<K>) {
listeners[name].push(fn);
}
export function emit<K extends keyof Events>(name: K, payload: Events[K]) {
listeners[name].forEach(fn => fn(payload));
}Also uses service.ts
import { NewOrderSchema } from "./schema.js";
import { Repository } from "./store.js";
import { STOCK, product } from "./catalog.js";
import { ok, fail, type Result } from "./result.js";
import { emit } from "./events.js";
import type { Order } from "./types.js";
export const orders = new Repository<Order>();
let nextId = 1042;
export function placeOrder(input: unknown): Result<Order> {
const parsed = NewOrderSchema.safeParse(input);
if (!parsed.success) return fail(parsed.error.issues[0].message);
for (const { sku, qty } of parsed.data.lines) {
if (!product(sku)) return fail(`unknown product ${sku}`);
if ((STOCK[sku] ?? 0) < qty) return fail(`not enough stock for ${sku}`);
}
parsed.data.lines.forEach(({ sku, qty }) => (STOCK[sku] -= qty));
const order = orders.save({ id: nextId++, ...parsed.data, status: "packing" });
emit("order.placed", order); return ok(order);
}Also uses cancel.ts
import { orders } from "./service.js";
import { ok, fail, type Result } from "./result.js";
import { emit } from "./events.js";
import type { Order } from "./types.js";
export function cancelOrder(id: number, reason: string): Result<Order> {
const order = orders.find(id);
if (!order) return fail(`order ${id} not found`);
if (order.status !== "packing") return fail(`order ${id} is ${order.status}, too late to cancel`);
const cancelled = orders.save({ ...order, status: "cancelled" });
emit("order.cancelled", { id, reason });
return ok(cancelled);
}Also uses reports.ts
import type { Order, Status } from "./types.js";
import { product } from "./catalog.js";
export type OrderSummary = Pick<Order, "id" | "customer" | "status"> & { total: number };
export function summarise(order: Order): OrderSummary {
const total = order.lines.reduce((sum, l) => sum + (product(l.sku)?.price ?? 0) * l.qty, 0);
return { id: order.id, customer: order.customer, status: order.status, total };
}
export function countByStatus(orders: Order[]): Record<Status, number> {
const counts: Record<Status, number> = { packing: 0, shipped: 0, delivered: 0, cancelled: 0 };
for (const o of orders) counts[o.status]++;
return counts;
}Also uses warehouse.ts
const WAREHOUSE: Record<string, number> = { "TRAIL-500": 5, "HELMET-M": 40, LIGHTS: 12 };
export async function warehouseStock(sku: string): Promise<number> {
await new Promise(resolve => setTimeout(resolve, 100)); // pretend network call
return WAREHOUSE[sku] ?? 0;
}Also uses cli.ts
import { placeOrder, orders } from "./service.js";
import { cancelOrder } from "./cancel.js";
import { summarise } from "./reports.js";
export function run(args: string[]): string {
const [command, ...rest] = args;
switch (command) {
case "place": {
const [customer, ...items] = rest;
const lines = items.map(i => ({ sku: i.split(":")[0], qty: Number(i.split(":")[1]) }));
const r = placeOrder({ customer, lines });
return r.ok ? `placed ${r.value.id}` : `error: ${r.error}`;
}
case "cancel": { const r = cancelOrder(Number(rest[0]), "customer request");
return r.ok ? `cancelled ${r.value.id}` : `error: ${r.error}`; }
case "list": return orders.all().map(o => JSON.stringify(summarise(o))).join("\n");
default: return "usage: place NAME SKU:QTY... | cancel ID | list";
}
}Summary
A small typed CLI turns words into library calls. Next, refactoring with the compiler's help.
Key takeaways- run(args)
- switch on command
- Typed calls
Next up: Project: Refactoring — the compiler helps