EasyJavaScriptTypeScript

Result<T, E> — Discriminated Union

TypeScriptTypesPatterns

The Result pattern replaces thrown exceptions with typed return values. It's a discriminated union — a union type with a shared field (ok) that TypeScript uses to narrow to the correct variant:

type Result<T, E = string> =
  | { ok: true;  value: T }   // success branch
  | { ok: false; error: E }   // failure branch

function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return err('Division by zero');
  return ok(a / b);
}

const result = divide(10, 0);
if (result.ok) {
  console.log(result.value);  // TypeScript: number ✅
} else {
  console.log(result.error);  // TypeScript: string ✅
}

Implement

FunctionSignatureDescription
ok(value)<T>(v: T) → Ok<T>Wraps a successful value
err(error)<E>(e: E) → Err<E>Wraps an error
unwrapOr(result, default)<T,E>(r: Result<T,E>, d: T) → TReturns value or default
isOk(result)<T,E>(r: Result<T,E>) → r is Ok<T>Type guard for success

The isOk return type result is Ok<T> is a type guard — calling it narrows result to the success branch.

Sample tests

Test #1ok wraps a number
Input: ["ok",42]
Output: {"ok":true,"value":42}
Test #2ok wraps a string
Input: ["ok","hello"]
Output: {"ok":true,"value":"hello"}
Test #3err wraps an error message
Input: ["err","Not found"]
Output: {"ok":false,"error":"Not found"}
Test #4unwrapOr returns value when ok
Input: ["unwrapOr",{"ok":true,"value":5},0]
Output: 5
Test #5unwrapOr returns default when err
Input: ["unwrapOr",{"ok":false,"error":"x"},99]
Output: 99
Test #6isOk returns true for Ok result
Input: ["isOk",{"ok":true,"value":1}]
Output: true
Test #7isOk returns false for Err result
Input: ["isOk",{"ok":false,"error":"oops"}]
Output: false