Skip to main content

Programming languages · Intermediate · 22 min

Narrow types safely with TypeScript discriminated unions

By Padding · Updated 18 Nov 2026
node:26 image · Node.js 26.13 · TypeScript 7.0.2

You will model a payment as a TypeScript 7 discriminated union, narrow it with switch, in, typeof, instanceof and your own type guards, parse untrusted JSON into it, and add a fourth state that the compiler tracks through every file that needs it.

On this page

A payment in most apps is in one of a few states. It is waiting, it went through, or it failed. Each state carries different facts: only a paid payment has a receipt, and only a failed one has a reason. If your type cannot say that, the compiler cannot stop you reading a receipt that does not exist, and the bug shows up in production as undefined on a customer's screen.

A discriminated union fixes this. You write one object type per state, give each a shared field with a fixed literal value (here status: "paid" and so on), and join them with |. TypeScript then uses that field to work out which state you are holding at each line of code. That process is called narrowing.

In this tutorial you build a small payments module on TypeScript 7.0.2 and Node.js 26. You start with the loose version most codebases have, replace it with a union, narrow it in every way the language offers, parse untrusted JSON into it, and finish with a state machine where adding a refunded state makes the compiler point at each place you need to change. Amounts are whole numbers in minor units (kobo for naira, cents for dollars), which avoids floating-point rounding on money.

Step 1 · Create the project

Make a throwaway project, install the compiler and Node's types at exact versions, and write a strict tsconfig.json. The settings match the ones explained in the TypeScript 7 set-up tutorial:

Bash
mkdir -p ~/payments-demo
cd ~/payments-demo
npm init -y
npm pkg set type=module
npm install --save-dev --save-exact typescript@7.0.2 @types/node@26.6.11
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src"]
}
JSON
mkdir -p src
npx tsc --version

strict matters most here. Without strictNullChecks, which strict turns on, an optional field reads as its plain type and most of what follows stops working.

Check it worked

npx tsc --version prints Version 7.0.2, and package.json lists both packages under devDependencies with no ^ in front, because of --save-exact.

Step 2 · See what optional fields let through

This is the shape you often find in existing code. One interface holds every field any state might need, and the state-specific ones are optional:

Bash
cat > src/loose.ts <<'TS'
interface LoosePayment {
  status: "pending" | "paid" | "failed";
  id: string;
  amount: number;
  paidAt?: string;
  receiptId?: string;
  failureReason?: string;
}

// Pending, yet it has a payment time and a failure reason. Nothing objects.
export const nonsense: LoosePayment = {
  status: "pending",
  id: "pay_001",
  amount: 250000,
  paidAt: "2026-11-20T09:05:00Z",
  failureReason: "card declined",
};

export function receiptLine(p: LoosePayment): string {
  if (p.status === "paid") {
    return `Receipt ${p.receiptId.toUpperCase()}`;
  }
  return "No receipt yet";
}
TS
npx tsc --noEmit > loose-errors.txt || echo "tsc exited with status $?"
cat loose-errors.txt

Check it worked

You see exactly one error, something like src/loose.ts(21,23): error TS18048: 'p.receiptId' is possibly 'undefined'. Look at what is missing. The nonsense object, which describes a payment that cannot exist, passes without a word. And inside if (p.status === "paid") the compiler still thinks receiptId may be missing, because nothing in the type links status to the other fields. The usual workaround, p.receiptId!, only silences the check.

Remove the file before you go on:

Bash
rm src/loose.ts loose-errors.txt

Step 3 · Model the payment as a discriminated union

Write one type per state. Every member has status with a different string literal, so status is the discriminant. Fields that only make sense in one state live only on that member, and none of them is optional:

Bash
cat > src/payment.ts <<'TS'
export type Pending = {
  status: "pending";
  id: string;
  amount: number;
  createdAt: string;
};

export type Paid = {
  status: "paid";
  id: string;
  amount: number;
  paidAt: string;
  receiptId: string;
};

export type Failed = {
  status: "failed";
  id: string;
  amount: number;
  reason: string;
  retryable: boolean;
};

export type Payment = Pending | Paid | Failed;
TS

Now try the same mistakes against the new type:

Bash
cat > src/mistakes.ts <<'TS'
import type { Payment } from "./payment.js";

export const extraField: Payment = {
  status: "pending",
  id: "pay_001",
  amount: 250000,
  createdAt: "2026-11-20T09:00:00Z",
  reason: "card declined",
};

export const missingField: Payment = {
  status: "paid",
  id: "pay_002",
  amount: 120000,
  paidAt: "2026-11-20T09:05:00Z",
};

export function receiptOfAnything(p: Payment): string {
  return p.receiptId;
}
TS
npx tsc --noEmit > mistakes.txt || echo "tsc exited with status $?"
cat mistakes.txt

Check it worked

The compiler reports three errors, one per mistake. The first says that reason does not exist in type Pending: TypeScript read status: "pending" and checked the rest of the object against that member only. The second says receiptId is missing from a Paid payment. The third says receiptId does not exist on type Payment, because a value you have not narrowed could be any of the three states. Delete the file:

Bash
rm src/mistakes.ts mistakes.txt

Step 4 · Narrow with switch, in, typeof and instanceof

Narrowing is TypeScript following your checks. After a test, it shrinks the type of the variable to whatever could pass that test. Add three sample payments to use from here on:

Bash
cat > src/samples.ts <<'TS'
import type { Payment } from "./payment.js";

export const samplePayments: Payment[] = [
  { status: "pending", id: "pay_101", amount: 250000, createdAt: "2026-11-20T09:00:00Z" },
  { status: "paid", id: "pay_102", amount: 120000, paidAt: "2026-11-20T09:05:00Z", receiptId: "RCT-7781" },
  { status: "failed", id: "pay_103", amount: 99000, reason: "insufficient funds", retryable: true },
];
TS

The main tool is a switch on the discriminant. Inside each case, p has the type of that one member, so p.receiptId is allowed under "paid" and an error anywhere else:

Bash
cat > src/describe.ts <<'TS'
import type { Payment } from "./payment.js";

export function describe(p: Payment): string {
  switch (p.status) {
    case "pending":
      return `${p.id} is waiting (since ${p.createdAt})`;
    case "paid":
      return `${p.id} is paid, receipt ${p.receiptId}`;
    case "failed":
      return `${p.id} failed: ${p.reason}${p.retryable ? " (can retry)" : ""}`;
  }
}
TS

The other three checks each suit a different kind of value:

Bash
cat > src/narrowing.ts <<'TS'
import type { Payment } from "./payment.js";

// `in` narrows to the members that declare the property.
export function receiptOf(p: Payment): string | null {
  if ("receiptId" in p) {
    return p.receiptId;
  }
  return null;
}

// `typeof` narrows primitives. An API sends minor units as a number;
// a form field sends major units as text, such as "1,200.50".
export function toMinorUnits(amount: number | string): number {
  if (typeof amount === "number") {
    return amount;
  }
  return Math.round(Number(amount.replaceAll(",", "")) * 100);
}

// `instanceof` narrows objects made by a class. A caught value is `unknown`,
// because JavaScript lets you throw anything.
export function messageOf(err: unknown): string {
  if (err instanceof Error) {
    return err.message;
  }
  return String(err);
}
TS
cat > src/demo-narrowing.ts <<'TS'
import { describe } from "./describe.js";
import { messageOf, receiptOf, toMinorUnits } from "./narrowing.js";
import { samplePayments } from "./samples.js";

for (const p of samplePayments) {
  console.log(describe(p));
}
console.log(samplePayments.map(receiptOf));
console.log(toMinorUnits(250000), toMinorUnits("1,200.50"));

for (const thrown of [new Error("gateway timeout"), "plain string"]) {
  try {
    throw thrown;
  } catch (err) {
    console.log(messageOf(err));
  }
}
TS
npx tsc
node dist/demo-narrowing.js

The switch in describe has no default, and the function still compiles with a string return type. TypeScript can see that the three cases cover every member, so the end of the function cannot be reached.

Check it worked

The program prints:

Text
pay_101 is waiting (since 2026-11-20T09:00:00Z)
pay_102 is paid, receipt RCT-7781
pay_103 failed: insufficient funds (can retry)
[ null, 'RCT-7781', null ]
250000 120050
gateway timeout
plain string

Prefer the discriminant over in for unions you own. in is tied to a field name, so it changes meaning when another state gains that field. You will see this happen in the last step.

Step 5 · Write a type guard and an assertion function

Sometimes you need a check you can reuse, or one TypeScript cannot work out from an expression. A type guard is a function whose return type is p is Paid: when it returns true, the caller's value is narrowed. An assertion function has the return type asserts p is Paid: it throws if the check fails, and every line after the call sees the narrowed type.

Bash
cat > src/guards.ts <<'TS'
import type { Paid, Payment } from "./payment.js";

export function isPaid(p: Payment): p is Paid {
  return p.status === "paid";
}

export function assertPaid(p: Payment): asserts p is Paid {
  if (p.status !== "paid") {
    throw new Error(`${p.id} is ${p.status}, not paid`);
  }
}
TS
cat > src/demo-guards.ts <<'TS'
import { assertPaid, isPaid } from "./guards.js";
import { messageOf } from "./narrowing.js";
import type { Payment } from "./payment.js";
import { samplePayments } from "./samples.js";

const paid = samplePayments.filter(isPaid);
const total = paid.reduce((sum, p) => sum + p.amount, 0);
console.log(paid.map((p) => p.receiptId), total);

function refundNote(p: Payment): string {
  assertPaid(p);
  return `refund against ${p.receiptId}`;
}

for (const p of samplePayments) {
  try {
    console.log(refundNote(p));
  } catch (err) {
    console.log(messageOf(err));
  }
}
TS
npx tsc
node dist/demo-guards.js

filter(isPaid) returns Paid[], so p.receiptId in the map needs no check. Since TypeScript 5.5 the compiler also infers a guard from a simple arrow function such as (p) => p.status === "paid", but a named guard documents the intent and can be reused.

Two cautions. First, TypeScript trusts the body of a guard completely. If you wrote return p.status !== "failed", it would still promise a Paid value and hand you pending payments with no receipt. Test guards like any other function. Second, an assertion function only works when it is called through a name with an explicit type. A function declaration, as here, is fine. An arrow function in a const without a type annotation gives error TS2775.

Check it worked

The output is:

Text
[ 'RCT-7781' ] 120000
pay_101 is pending, not paid
refund against RCT-7781
pay_103 is failed, not paid

Step 6 · Make the compiler check every case

describe covers all three states today. What you want is an error the day someone adds a fourth. The standard tool is a function that only accepts never, the type with no values. In the default branch of a complete switch, nothing is left, so p has type never and the call compiles. If a state is unhandled, p still has that state's type and the call fails.

For lookup tables, the satisfies operator does the same job. It checks that an object matches a type without changing the type TypeScript infers for it. With as const, each label keeps its literal type, such as "Paid", instead of being widened to string.

Bash
cat > src/assert-never.ts <<'TS'
export function assertNever(value: never): never {
  throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}
TS
cat > src/describe.ts <<'TS'
import { assertNever } from "./assert-never.js";
import type { Payment } from "./payment.js";

export const statusLabels = {
  pending: "Awaiting payment",
  paid: "Paid",
  failed: "Payment failed",
} as const satisfies Record<Payment["status"], string>;

export function describe(p: Payment): string {
  switch (p.status) {
    case "pending":
      return `${p.id} is waiting (since ${p.createdAt})`;
    case "paid":
      return `${p.id} is paid, receipt ${p.receiptId}`;
    case "failed":
      return `${p.id} failed: ${p.reason}${p.retryable ? " (can retry)" : ""}`;
    default:
      return assertNever(p);
  }
}
TS
npx tsc --noEmit

Payment["status"] reads the type of the status field from the union: "pending" | "paid" | "failed". Record of that type means one entry per state, no more and no fewer. assertNever also throws at run time, which protects you when bad data slips past the types, for example from an old client or a database row written by hand.

Check it worked

npx tsc --noEmit prints nothing. To see the check fire, write a switch that forgets a case:

Bash
cat > src/forgot.ts <<'TS'
import { assertNever } from "./assert-never.js";
import type { Payment } from "./payment.js";

export function shortCode(p: Payment): string {
  switch (p.status) {
    case "pending":
      return "PEN";
    case "paid":
      return "PAD";
    default:
      return assertNever(p);
  }
}
TS
npx tsc --noEmit > forgot.txt || echo "tsc exited with status $?"
cat forgot.txt
rm src/forgot.ts forgot.txt

The error says something like Argument of type 'Failed' is not assignable to parameter of type 'never'. It names the member you forgot, which is the useful part.

Step 7 · Parse unknown JSON into the union

Types disappear when the program runs. Anything that arrives from outside, such as a webhook body, a file or a message from a mobile client, has whatever shape the sender gave it. JSON.parse returns any, which switches checking off. Store its result as unknown instead, then narrow your way to a Payment one field at a time.

The parser below has small field readers in fields.ts and a table with one function per state, and satisfies makes sure the table has an entry for every status. The mapped type { [S in Payment["status"]]: ... } says that the "paid" entry must return a Paid, and so on:

Bash
cat > src/fields.ts <<'TS'
export type Fields = Record<string, unknown>;

export function text(r: Fields, key: string): string {
  const v = r[key];
  if (typeof v !== "string") throw new Error(`${key} must be a string`);
  return v;
}

export function minorUnits(r: Fields, key: string): number {
  const v = r[key];
  if (typeof v !== "number" || !Number.isInteger(v)) {
    throw new Error(`${key} must be a whole number of minor units`);
  }
  return v;
}

export function flag(r: Fields, key: string): boolean {
  const v = r[key];
  if (typeof v !== "boolean") throw new Error(`${key} must be true or false`);
  return v;
}
TS
cat > src/parsers.ts <<'TS'
import { flag, minorUnits, text, type Fields } from "./fields.js";
import type { Payment } from "./payment.js";

export const parsers = {
  pending: (r) => ({
    status: "pending",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    createdAt: text(r, "createdAt"),
  }),
  paid: (r) => ({
    status: "paid",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    paidAt: text(r, "paidAt"),
    receiptId: text(r, "receiptId"),
  }),
  failed: (r) => ({
    status: "failed",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    reason: text(r, "reason"),
    retryable: flag(r, "retryable"),
  }),
} satisfies { [S in Payment["status"]]: (r: Fields) => Extract<Payment, { status: S }> };
TS
cat > src/parse.ts <<'TS'
import type { Fields } from "./fields.js";
import { parsers } from "./parsers.js";
import type { Payment } from "./payment.js";

function isFields(v: unknown): v is Fields {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

function isStatus(v: unknown): v is Payment["status"] {
  return typeof v === "string" && Object.hasOwn(parsers, v);
}

export function parsePayment(input: unknown): Payment {
  if (!isFields(input)) throw new Error("a payment must be a JSON object");
  const status = input["status"];
  if (!isStatus(status)) throw new Error(`unknown status ${JSON.stringify(status)}`);
  return parsers[status](input);
}
TS

isStatus checks the table itself, so the list of valid statuses lives in one place. Now feed it a file with two good records and two bad ones, plus a body that is not JSON at all, as you get when a connection drops halfway through a response on a weak mobile signal:

Bash
cat > payments.json <<'JSON'
[
  { "status": "paid", "id": "pay_201", "amount": 500000, "paidAt": "2026-11-21T10:00:00Z", "receiptId": "RCT-9001" },
  { "status": "failed", "id": "pay_202", "amount": 75000, "reason": "card expired", "retryable": false },
  { "status": "paid", "id": "pay_203", "amount": "5000" },
  { "status": "chargeback", "id": "pay_204", "amount": 1000 }
]
JSON
cat > src/main.ts <<'TS'
import { readFileSync } from "node:fs";
import { describe } from "./describe.js";
import { messageOf } from "./narrowing.js";
import { parsePayment } from "./parse.js";

function load(body: string): unknown {
  try {
    return JSON.parse(body);
  } catch (err) {
    if (err instanceof SyntaxError) {
      console.log("not valid JSON, ignoring the body");
      return [];
    }
    throw err;
  }
}

load('[{"status": "paid", "id": "pay_2');

const data = load(readFileSync("payments.json", "utf8"));
if (!Array.isArray(data)) throw new Error("expected a list of payments");

data.forEach((item: unknown, i) => {
  try {
    console.log(describe(parsePayment(item)));
  } catch (err) {
    console.log(`rejected item ${i + 1}: ${messageOf(err)}`);
  }
});
TS
npx tsc
node dist/main.js

Writing a parser by hand shows what has to happen. In a larger app, a schema library such as Zod or Valibot gives you the same checks with less code and infers the type from the schema. The idea is the same: data from outside starts as unknown and becomes a Payment only after a check.

Check it worked

The output is:

Text
not valid JSON, ignoring the body
pay_201 is paid, receipt RCT-9001
pay_202 failed: card expired
rejected item 3: amount must be a whole number of minor units
rejected item 4: unknown status "chargeback"

Item 3 sent its amount as text, and item 4 has a status the app does not know. Both are stopped at the edge with a clear message, and the rest of the program only ever sees valid payments.

Step 8 · Build a reducer and add a fourth state

A reducer takes the current state and an event and returns the next state. Events are a discriminated union too, on type. A pending payment can succeed or be declined, and a failed one can be retried if the gateway said so:

Bash
cat > src/reducer.ts <<'TS'
import { assertNever } from "./assert-never.js";
import type { Payment } from "./payment.js";

export type PaymentEvent =
  | { type: "succeeded"; at: string; receiptId: string }
  | { type: "declined"; reason: string; retryable: boolean }
  | { type: "retried"; at: string };

export function reduce(p: Payment, e: PaymentEvent): Payment {
  switch (p.status) {
    case "pending":
      if (e.type === "succeeded") {
        return { status: "paid", id: p.id, amount: p.amount, paidAt: e.at, receiptId: e.receiptId };
      }
      if (e.type === "declined") {
        return { status: "failed", id: p.id, amount: p.amount, reason: e.reason, retryable: e.retryable };
      }
      return p;
    case "failed":
      if (e.type === "retried" && p.retryable) {
        return { status: "pending", id: p.id, amount: p.amount, createdAt: e.at };
      }
      return p;
    case "paid":
      return p;
    default:
      return assertNever(p);
  }
}
TS
cat > src/replay.ts <<'TS'
import type { Payment } from "./payment.js";
import { reduce, type PaymentEvent } from "./reducer.js";

let payment: Payment = { status: "pending", id: "pay_301", amount: 180000, createdAt: "2026-11-22T08:00:00Z" };
const events: PaymentEvent[] = [
  { type: "declined", reason: "network timeout", retryable: true },
  { type: "retried", at: "2026-11-22T08:02:00Z" },
  { type: "succeeded", at: "2026-11-22T08:02:30Z", receiptId: "RCT-4410" },
];

const history: string[] = [payment.status];
for (const e of events) {
  payment = reduce(payment, e);
  history.push(payment.status);
}
console.log(history.join(" -> "));
TS
npx tsc
node dist/replay.js

The output is pending -> failed -> pending -> paid.

Now the product team asks for refunds. Add a Refunded member to the union. A refund keeps the receipt it was made against:

Bash
cat > src/payment.ts <<'TS'
export type Pending = {
  status: "pending";
  id: string;
  amount: number;
  createdAt: string;
};

export type Paid = {
  status: "paid";
  id: string;
  amount: number;
  paidAt: string;
  receiptId: string;
};

export type Failed = {
  status: "failed";
  id: string;
  amount: number;
  reason: string;
  retryable: boolean;
};

export type Refunded = {
  status: "refunded";
  id: string;
  amount: number;
  receiptId: string;
  refundedAt: string;
};

export type Payment = Pending | Paid | Failed | Refunded;
TS
npx tsc --noEmit > refund-errors.txt || echo "tsc exited with status $?"
cat refund-errors.txt

Read the list. Each error is a place that has to decide what a refund means:

  • src/describe.ts, twice: statusLabels no longer satisfies its Record because refunded is missing, and the default branch of describe now receives a Refunded where it expects never.
  • src/parsers.ts: the table has no refunded entry, so incoming refunds would be rejected.
  • src/parse.ts: isStatus now accepts "refunded", but the table it indexes has no such key. This error goes away when the table is fixed.
  • src/reducer.ts: the default branch receives a Refunded.

Notice what is not on the list. receiptOf in src/narrowing.ts uses "receiptId" in p, and Refunded also has receiptId, so it now returns receipts for refunded payments without any error. That may be what you want or it may not. The compiler cannot tell, which is why the discriminant is the safer check.

Make the changes. Add the label and the case to describe.ts:

Bash
cat > src/describe.ts <<'TS'
import { assertNever } from "./assert-never.js";
import type { Payment } from "./payment.js";

export const statusLabels = {
  pending: "Awaiting payment",
  paid: "Paid",
  failed: "Payment failed",
  refunded: "Refunded",
} as const satisfies Record<Payment["status"], string>;

export function describe(p: Payment): string {
  switch (p.status) {
    case "pending":
      return `${p.id} is waiting (since ${p.createdAt})`;
    case "paid":
      return `${p.id} is paid, receipt ${p.receiptId}`;
    case "failed":
      return `${p.id} failed: ${p.reason}${p.retryable ? " (can retry)" : ""}`;
    case "refunded":
      return `${p.id} was refunded on ${p.refundedAt} against ${p.receiptId}`;
    default:
      return assertNever(p);
  }
}
TS

Add a refunded entry to the parser table in src/parsers.ts:

Bash
cat > src/parsers.ts <<'TS'
import { flag, minorUnits, text, type Fields } from "./fields.js";
import type { Payment } from "./payment.js";

export const parsers = {
  pending: (r) => ({
    status: "pending",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    createdAt: text(r, "createdAt"),
  }),
  paid: (r) => ({
    status: "paid",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    paidAt: text(r, "paidAt"),
    receiptId: text(r, "receiptId"),
  }),
  failed: (r) => ({
    status: "failed",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    reason: text(r, "reason"),
    retryable: flag(r, "retryable"),
  }),
  refunded: (r) => ({
    status: "refunded",
    id: text(r, "id"),
    amount: minorUnits(r, "amount"),
    receiptId: text(r, "receiptId"),
    refundedAt: text(r, "refundedAt"),
  }),
} satisfies { [S in Payment["status"]]: (r: Fields) => Extract<Payment, { status: S }> };
TS

Then teach the reducer a refunded event, which only a paid payment accepts. Refunded is a final state:

Bash
cat > src/reducer.ts <<'TS'
import { assertNever } from "./assert-never.js";
import type { Payment } from "./payment.js";

export type PaymentEvent =
  | { type: "succeeded"; at: string; receiptId: string }
  | { type: "declined"; reason: string; retryable: boolean }
  | { type: "retried"; at: string }
  | { type: "refunded"; at: string };

export function reduce(p: Payment, e: PaymentEvent): Payment {
  switch (p.status) {
    case "pending":
      if (e.type === "succeeded") {
        return { status: "paid", id: p.id, amount: p.amount, paidAt: e.at, receiptId: e.receiptId };
      }
      if (e.type === "declined") {
        return { status: "failed", id: p.id, amount: p.amount, reason: e.reason, retryable: e.retryable };
      }
      return p;
    case "failed":
      if (e.type === "retried" && p.retryable) {
        return { status: "pending", id: p.id, amount: p.amount, createdAt: e.at };
      }
      return p;
    case "paid":
      if (e.type === "refunded") {
        return { status: "refunded", id: p.id, amount: p.amount, receiptId: p.receiptId, refundedAt: e.at };
      }
      return p;
    case "refunded":
      return p;
    default:
      return assertNever(p);
  }
}
TS
cat >> src/replay.ts <<'TS'

payment = reduce(payment, { type: "refunded", at: "2026-11-23T12:00:00Z" });
console.log(payment.status, payment.status === "refunded" ? payment.refundedAt : "");
TS
npx tsc
node dist/replay.js

Check it worked

npx tsc prints nothing, and the replay prints two lines:

Text
pending -> failed -> pending -> paid
refunded 2026-11-23T12:00:00Z

The compiler found every switch and table that needed the new state. It did not decide what a refund should do in each place; you did. Before you ship a change like this, read the in checks and any code that handles statuses as plain strings, because those are outside what the union can protect.

Step 9 · Clean up

Remove the demo project. Node.js stays installed:

Bash
cd ~
rm -rf ~/payments-demo

Check it worked

ls ~/payments-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.