Aliased Conditions Narrow Discriminated Unions
Hoist a discriminant check into a const boolean once and every later branch inherits the narrowing — no repeated event.kind comparisons.
Code
type OrderEvent =
| { kind: 'paid'; orderId: string; amountCents: number }
| { kind: 'refunded'; orderId: string; reason: string };
// Hoist the discriminant test into a const boolean: TS carries the
// narrowing through the alias (aliased conditions, TypeScript 4.4+).
function describe(event: OrderEvent): string {
const isRefund = event.kind === 'refunded';
if (isRefund) {
// event is the refunded variant here — no second event.kind check
return `refund ${event.orderId}: ${event.reason}`;
}
return `paid ${event.orderId}: ${(event.amountCents / 100).toFixed(2)}`;
}
// Aliasing also works on a destructured discriminant
function label(event: OrderEvent): string {
const { kind } = event;
const refund = kind === 'refunded';
return refund ? `reason on file: ${event.reason}` : 'payment received';
}
const inbox: OrderEvent[] = [
{ kind: 'paid', orderId: 'o-1', amountCents: 4950 },
{ kind: 'refunded', orderId: 'o-2', reason: 'duplicate charge' },
];
for (const event of inbox) {
console.log(describe(event));
console.log(label(event));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
paid o-1: 49.50
payment received
refund o-2: duplicate charge
reason on file: duplicate chargeHow the pieces connect
The snippet is organized around the functions describe and label.
Iteration happens inside for (const event of inbox) — everything outside it runs once.
What to watch for
- All standard-library: copy it into a project and it just runs.
- The guard
isRefundexits the flow throughreturnwhen its condition holds.
Using it
Entry signature: function describe(event: OrderEvent)
Key statements
return `paid ${event.orderId}: ${(event.amountCents / 100).toFixed(2)}`;
return refund ? `reason on file: ${event.reason}` : 'payment received';
return `refund ${event.orderId}: ${event.reason}`;
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `describe`, `label` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.