Narrow a union with a type guard

Typescript

A predicate returning `x is T` teaches the compiler what a runtime check proved.

type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function isOk<T>(r: Result<T>): r is { ok: true; value: T } {
  return r.ok;
}

if (isOk(result)) {
  console.log(result.value); // narrowed
}

More in TypeScript

Random picks