typescript

Result Type Pattern

Handle errors without try-catch using Result type

Tarun Sharma
Tarun SharmaJanuary 15, 2024 ยท 1 min read ยท Last Updated:
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

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

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

async function safeAsync<T>(promise: Promise<T>): Promise<Result<T, Error>> {
  try {
    const value = await promise;
    return ok(value);
  } catch (error) {
    return err(error instanceof Error ? error : new Error(String(error)));
  }
}

Usage

async function fetchUser(id: number): Promise<Result<User, string>> {
  const response = await fetch(`/api/users/${id}`);

  if (!response.ok) {
    return err(`Failed to fetch user: ${response.status}`);
  }

  const user = await response.json();
  return ok(user);
}

// No try-catch needed
const result = await fetchUser(1);

if (result.ok) {
  console.log(result.value.name); // Type-safe access
} else {
  console.error(result.error); // Error handling
}

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16