Unknown Type Guard Narrowing

Narrow unknown values safely with composable type guards, exhaustive switch on discriminants, and assertion helpers that throw precisely.

TypescriptData Integrity

Code

typescriptsnippet
39 lines
interface Success<T> { status: 'success'; data: T }
interface Failure { status: 'failure'; code: number; message: string }
type Outcome<T> = Success<T> | Failure;

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function hasKeys<K extends string>(
  value: unknown, ...keys: K[]
): value is Record<K, unknown> {
  return isRecord(value) && keys.every((k) => k in value);
}

function parseOutcome(raw: unknown): Outcome<string> {
  if (!hasKeys(raw, 'status')) {
    throw new TypeError('outcome requires a status field');
  }
  switch (raw.status) {
    case 'success':
      if (typeof raw.data !== 'string') {
        throw new TypeError('success outcome needs string data');
      }
      return { status: 'success', data: raw.data };
    case 'failure':
      if (!hasKeys(raw, 'code', 'message')) {
        throw new TypeError('failure outcome needs code and message');
      }
      if (typeof raw.code !== 'number' || typeof raw.message !== 'string') {
        throw new TypeError('failure fields have wrong types');
      }
      return { status: 'failure', code: raw.code, message: raw.message };
    default:
      throw new TypeError('unknown status: ' + String(raw.status));
  }
}

const ok = parseOutcome(JSON.parse('{"status":"success","data":"hello"}'));
console.log(ok.status === 'success' ? ok.data.toUpperCase() : 'n/a');

Output

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

HELLO

How the snippet is structured

Unknown Type Guard Narrowing is built around the functions isRecord, hasKeys and parseOutcome.

When the guard condition holds, TypeError is thrown rather than a bogus value returned.

The result is a fresh construction, so callers can keep their originals.

Caveats

  • The guard typeof raw.data !== 'string' short-circuits the flow with an early throw when its condition holds.

Putting it to use

The main signature is function isRecord(value: unknown)

Core lines

return isRecord(value) && keys.every((k) => k in value);
return typeof value === 'object' && value !== null && !Array.isArray(value);
return { status: 'failure', code: raw.code, message: raw.message };

Interactive Tools for This Topic

FAQ

Does `isRecord` modify its input?
It does not. Inputs are only read; the return value is freshly built.
How does the snippet fail?
Validation comes first — `TypeError` marks the failure at `typeof raw.data !== 'string'`, before any partial work happens.
Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `isRecord`, `hasKeys`, `parseOutcome` at load time.