A checkout form needs a store name for pickup and a street address for delivery. If you model both as optional strings on one object, the compiler will accept a pickup request that has an address but no store. The error then shows up when you try to print a confirmation. In this example each checkout method gets its own object type, and data from outside the program is checked before it can reach the confirmation function.

Download the complete TypeScript checkout example (ZIP). It includes the two TypeScript files, project configuration, npm lockfile, README and automated tests.

Set up the example

Use Node.js 20 or newer with npm. Extract the ZIP, open a terminal in the typescript-checkout-fulfillment folder and run the commands below. If you are creating the files from the article, run npm install once to create your lockfile in place of npm ci. The project pins TypeScript 5.9.3 so the same compiler runs on each installation. It has no runtime dependencies.

npm ci
npm run build
npm run --silent demo
npm test

Save the following as package.json. The build script compiles the TypeScript into JavaScript and the demo script runs the compiled program with Node.js.

{
  "name": "toolzify-typescript-checkout-fulfillment",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "demo": "node dist/demo.js",
    "test": "npm run --silent build && node --test fulfillment.test.cjs"
  },
  "devDependencies": {
    "typescript": "5.9.3"
  }
}

Save this configuration as tsconfig.json. It turns on strict checking and stops a failed build from emitting new JavaScript into dist. If a build fails, fix the error before running the demo again because an older successful build can still be present.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "noEmitOnError": true,
    "outDir": "dist"
  },
  "include": ["fulfillment.ts", "demo.ts"]
}

Model and validate the two checkout methods

In Fulfillment, method appears in both members with a different literal value. That makes it the discriminant. Inside the pickup branch of confirmation, TypeScript narrows the order to the member that has a store. In the delivery branch, the order has an address. Each branch can read its own field without a cast or an optional field check.

Data from a form or API still needs runtime validation. parseFulfillment starts with unknown, rejects missing or unsupported methods, then requires the string associated with that method. It trims that string and constructs a fresh object with the fields the application uses. This example checks for nonempty text. A checkout accepting real orders would also look up the store and verify that the address is in its delivery area.

Save the complete model, parser and confirmation function as fulfillment.ts.

export type Fulfillment =
  | { method: "pickup"; store: string }
  | { method: "delivery"; address: string };

function requiredText(value: unknown, field: string): string {
  if (typeof value !== "string" || value.trim() === "") {
    throw new Error(`${field} must be a non-empty string.`);
  }
  return value.trim();
}

export function parseFulfillment(input: unknown): Fulfillment {
  if (
    typeof input !== "object" ||
    input === null ||
    Array.isArray(input) ||
    !("method" in input)
  ) {
    throw new Error("Expected a checkout object with a method.");
  }

  switch (input.method) {
    case "pickup":
      return {
        method: "pickup",
        store: requiredText("store" in input ? input.store : undefined, "store"),
      };
    case "delivery":
      return {
        method: "delivery",
        address: requiredText(
          "address" in input ? input.address : undefined,
          "address",
        ),
      };
    default:
      throw new Error("method must be pickup or delivery.");
  }
}

export function confirmation(order: Fulfillment): string {
  switch (order.method) {
    case "pickup":
      return `Pick up your order at ${order.store}.`;
    case "delivery":
      return `We will deliver your order to ${order.address}.`;
    default: {
      const unhandled: never = order;
      throw new Error(`Unhandled fulfillment method: ${JSON.stringify(unhandled)}`);
    }
  }
}

Run the example and check its output

Save this file as demo.ts. The three sample requests model what might arrive from a checkout form. The first contains extra whitespace, the second uses a delivery address, and the third sends a delivery field with a pickup method.

import { confirmation, parseFulfillment } from "./fulfillment";

const requests: unknown[] = [
  { method: "pickup", store: " Central Market " },
  { method: "delivery", address: "18 Maple Lane" },
  { method: "pickup", address: "18 Maple Lane" },
];

for (const request of requests) {
  try {
    console.log(confirmation(parseFulfillment(request)));
  } catch (error) {
    if (!(error instanceof Error)) throw error;
    console.log(`Rejected: ${error.message}`);
  }
}

Run npm run build and then npm run --silent demo. The first two messages use the appropriate fields. The rejection on the third line is intentional.

Pick up your order at Central Market.
We will deliver your order to 18 Maple Lane.
Rejected: store must be a non-empty string.

Check invalid input

A missing or blank store produces the pickup error shown above. A delivery with a missing, blank or numeric address produces address must be a non-empty string. An unsupported value such as courier produces method must be pickup or delivery. Pass the original request through the parser before calling confirmation so those errors identify the invalid input at the boundary.

Save the following as fulfillment.test.cjs and run npm test. The tests check both confirmation messages, the shape of the parsed objects and the input errors.

const assert = require("node:assert/strict");
const { test } = require("node:test");
const { confirmation, parseFulfillment } = require("./dist/fulfillment.js");

test("pickup trims the store and produces a pickup message", () => {
  const order = parseFulfillment({ method: "pickup", store: " Central Market " });
  assert.deepEqual(order, { method: "pickup", store: "Central Market" });
  assert.equal(confirmation(order), "Pick up your order at Central Market.");
});

test("delivery keeps its address and discards unrelated input", () => {
  const order = parseFulfillment({
    method: "delivery",
    address: "18 Maple Lane",
    store: "Central Market",
  });
  assert.deepEqual(order, { method: "delivery", address: "18 Maple Lane" });
  assert.equal(confirmation(order), "We will deliver your order to 18 Maple Lane.");
});

for (const [label, input, message] of [
  ["null", null, "Expected a checkout object with a method."],
  ["array", [], "Expected a checkout object with a method."],
  ["missing method", {}, "Expected a checkout object with a method."],
  ["unknown method", { method: "courier" }, "method must be pickup or delivery."],
  ["wrong method type", { method: 7 }, "method must be pickup or delivery."],
  ["pickup without store", { method: "pickup", address: "Maple Lane" }, "store must be a non-empty string."],
  ["missing delivery address", { method: "delivery" }, "address must be a non-empty string."],
  ["blank delivery address", { method: "delivery", address: "  " }, "address must be a non-empty string."],
  ["numeric delivery address", { method: "delivery", address: 18 }, "address must be a non-empty string."],
]) {
  test(`rejects ${label}`, () => {
    assert.throws(() => parseFulfillment(input), { message });
  });
}

Let the compiler find a missing branch

Add | { method: "locker"; lockerId: string } to the union before its semicolon, then build again. In the default branch of confirmation, the remaining value can now be a locker order. The compiler rejects its assignment to never because the switch has not handled it. Supporting lockers requires both a parser branch that validates lockerId and a confirmation branch that uses it. Restore the two original members to run the supplied tests again.

Further reading: the TypeScript handbook on narrowing and exhaustiveness and the TypeScript compiler reference for strict mode.