Exhaustive switch true For Multi-Rule Routing

Combine ordered predicates and type guards inside switch (true) to narrow union events and numeric thresholds without deeply nested if-else chains.

TypescriptResilience

Code

snippet
type UpstreamOutcome =
  | { kind: 'http'; status: number; body: string }
  | { kind: 'timeout'; elapsedMs: number }
  | { kind: 'network'; code: string };

function classifyOutcome(res: UpstreamOutcome): 'retry' | 'ok' | 'reject' {
  // switch (true) narrows `res` inside each case body based on its predicate
  switch (true) {
    case res.kind === 'network':
      console.log('transport failure:', res.code);
      return 'retry';
    case res.kind === 'timeout' && res.elapsedMs >= 1000:
      console.log('slow timeout:', res.elapsedMs);
      return 'retry';
    case res.kind === 'http' && (res.status === 429 || res.status >= 500):
      console.log('transient status:', res.status);
      return 'retry';
    case res.kind === 'http' && res.status >= 200 && res.status < 300:
      return 'ok';
    default:
      return 'reject';
  }
}

const samples: UpstreamOutcome[] = [
  { kind: 'http', status: 200, body: 'ok' },
  { kind: 'http', status: 503, body: 'busy' },
  { kind: 'timeout', elapsedMs: 1500 },
  { kind: 'http', status: 400, body: 'bad input' },
  { kind: 'network', code: 'ECONNRESET' },
];
console.log('decisions:', samples.map(classifyOutcome).join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

transient status: 503
slow timeout: 1500
transport failure: ECONNRESET
decisions: ok,retry,retry,reject,retry

How the snippet works

Exhaustive switch true For Multi-Rule Routing keeps everything in the function classifyOutcome.

Points of care

  • Copy, run: the standard library answers every call in the file.

Using it

Signature: function classifyOutcome(res: UpstreamOutcome)

The run emits 4 labeled sections — transport failure:, slow timeout:, transient status:, decisions: — one per step.

Key statements

return 'reject';
return 'retry';
return 'ok';

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `classifyOutcome` at load time.