Typed Result for Error Handling

Model success and failure as a discriminated Result type instead of throwing, forcing callers to handle the error branch explicitly at compile time.

TypescriptResilience

Code

typescriptsnippet
23 lines
export type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

export function ok<T>(value: T): Result<T, never> {
  return { ok: true, value };
}

export function fail<E>(error: E): Result<never, E> {
  return { ok: false, error };
}

export function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T {
  return result.ok ? result.value : fallback;
}

export async function tryCatch<T>(fn: () => Promise<T>): Promise<Result<T>> {
  try {
    return ok(await fn());
  } catch (error) {
    return fail(error instanceof Error ? error : new Error(String(error)));
  }
}

How it works

Typed Result for Error Handling keeps everything in the functions ok, fail, unwrapOr and tryCatch.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying true.

Applying it

The surface worth importing is ok; the helpers around it are private to the snippet.

The call returns true.

Statements that matter

export async function tryCatch<T>(fn: () => Promise<T>): Promise<Result<T>> {
  try {
    return ok(await fn());
  } catch (error) {
    return fail(error instanceof Error ? error : new Error(String(error)));
  }
}
return result.ok ? result.value : fallback;
return { ok: false, error };

Interactive Tools for This Topic

FAQ

Does `ok` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `ok`, `fail`, `unwrapOr` at load time.