Article TypeScript

Article

TypeScript Union Types for Payment Results

A practical introduction to TypeScript union types with a type-safe checkout result.

1 min read TypeScript

A TypeScript union says that a value may be one of several types. Use | to join the allowed members:

type PaymentProvider = 'paypal' | 'stripe';

That small type prevents a provider from being anything other than 'paypal' or 'stripe'. Unions become especially useful when the allowed values have different object shapes.

Model a checkout result

A payment attempt does not always return the same data. A successful attempt has a transaction ID; a failed one has a reason. A discriminated union represents both outcomes honestly:

type PaymentSuccess = {
  status: 'success';
  provider: PaymentProvider;
  transactionId: string;
};

type PaymentFailure = {
  status: 'failure';
  reason: 'card_declined' | 'payment_cancelled';
  retryable: boolean;
};

type PaymentResult = PaymentSuccess | PaymentFailure;

The status property is the discriminant: its literal value tells TypeScript which member of PaymentResult it has.

Narrow before using member-specific data

When a value is a union, TypeScript only allows operations that work for every member. transactionId exists only on PaymentSuccess, so access it after narrowing with status:

function getCheckoutMessage(result: PaymentResult): string {
  if (result.status === 'success') {
    return `Payment ${result.transactionId} completed with ${result.provider}.`;
  }

  return result.retryable
    ? `Payment failed: ${result.reason}. Please try again.`
    : `Payment failed: ${result.reason}. Choose another payment method.`;
}

Inside the if, result is a PaymentSuccess. After that branch returns, it is a PaymentFailure. This is called narrowing: TypeScript uses the check already present in the JavaScript code to make the type more specific.

Keep future states visible

For state unions that may grow, an exhaustive switch makes missing handling obvious:

function assertNever(value: never): never {
  throw new Error(`Unhandled payment result: ${JSON.stringify(value)}`);
}

function getStatusLabel(result: PaymentResult): string {
  switch (result.status) {
    case 'success':
      return 'Paid';
    case 'failure':
      return 'Payment failed';
    default:
      return assertNever(result);
  }
}

If a later PaymentPending member is added to PaymentResult, the call to assertNever becomes a type error until the new case is handled.

Union types do not add runtime behavior or validation. They make the TypeScript contract precise; data from an API still needs validation at the boundary. Once the value is trusted, a discriminated union keeps the rest of the application clear about the states it can receive.

Reference

Related articles

Keep reading

Search

Search the publication

Search articles and topic pages without leaving the page.