TypeScript Result Type for Error Handling

3.5.2 · active · verified Sun Apr 19

The `typescript-result` package provides a robust, type-safe `Result` type, inspired by Rust's `Result` enum, for managing operations that can succeed or fail without relying on traditional `try-catch` blocks or throwing exceptions. It aims to transform chaotic error handling into elegant, functional code by enforcing explicit error handling at compile time. The current stable version is 3.5.2, with active development indicated by recent beta releases (e.g., v3.6.0-beta.3) that frequently introduce new features and fixes. Key differentiators include explicit `Ok` and `Err` variants, methods like `isOk()`, `isError()`, `map()`, `mapErr()`, and the recently added `match()` for basic pattern matching on error types. It targets modern Node.js environments (`>=18`) and is designed for seamless integration into TypeScript projects, improving code predictability and maintainability compared to implicit exception propagation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates asynchronous `Result` usage, basic error checking with `isOk()`, accessing `value` or `error`, and handling different error types using the `match()` method.

import { Result, Ok, Err } from 'typescript-result';

interface User { id: string; name: string; }

// Simulate a database operation that might fail
async function getUserById(id: string): Promise<Result<User, Error>> {
  return new Promise(resolve => {
    setTimeout(() => {
      if (id === '123') {
        resolve(Ok({ id: '123', name: 'Alice' }));
      } else if (id === 'error') {
        resolve(Err(new Error('Database error: Failed to fetch user.')));
      } else {
        resolve(Err(new Error('User not found.')));
      }
    }, 100);
  });
}

async function processUser(userId: string) {
  const userResult = await getUserById(userId);

  if (userResult.isOk()) {
    console.log(`Successfully fetched user: ${userResult.value.name}`);
    // Further processing with userResult.value
  } else {
    console.error(`Failed to fetch user: ${userResult.error.message}`);
    // Handle specific errors using match() available since v3.5.0
    userResult
      .match()
      .when(Error, (err) => {
        if (err.message.includes('not found')) {
          console.warn('User ID not recognized.');
        } else {
          console.error(`Unhandled error type: ${err.message}`);
        }
      })
      .run();
  }
}

processUser('123'); // Success
processUser('456'); // User not found
processUser('error'); // Database error

view raw JSON →