Structured Error Handling for TypeScript

The Result Library is a TypeScript utility designed to offer structured error handling using Ok and Err types, providing a robust way to manage both success and failure scenarios. This library is inspired by Rust, borrowing its error-handling patterns to create a reliable alternative to exception-based error management.


Features

  • Type Safety: Explicit handling of Ok and Err cases with strong TypeScript typings.

  • Convenient API: Simplifies error handling with intuitive methods.

  • Improved Error Handling: Reduce runtime errors with structured control flows.

  • Reusable Components: Seamlessly integrates into any TypeScript project.


Installation

npm install result-library

Usage

Creating Results

To create Ok and Err results, use the ResultBuilder interface:

import { ResultBuilder } from 'result-library';

const { Ok, Err } = ResultBuilder();

const success = Ok("Operation was successful");
const failure = Err("An error occurred");

Checking Results

if (success.is_ok()) {
  console.log("Success:", success.unwrap());
} else {
  console.error("Error:", success.err());
}

if (failure.is_err()) {
  console.error("Failure:", failure.unwrap_err());
}

Example: Division Function

function divide(a: number, b: number) {
  const { Ok, Err } = ResultBuilder();
  if (b === 0) {
    return Err("Division by zero is not allowed");
  }
  return Ok(a / b);
}

const result = divide(10, 2);
if (result.is_ok()) {
  console.log("Result:", result.unwrap());
} else {
  console.error("Error:", result.unwrap_err());
}

Advanced Usage with Types

Define explicit types for better type safety:

const { Ok, Err } = ResultBuilder<number, string>();
const result = Ok(42);
const error = Err("Something went wrong");

if (result.is_ok()) {
  console.log(result.unwrap());
} else {
  console.error(result.unwrap_err());
}

Use Case: File Processing

function processFile(filePath: string) {
  const { Ok, Err } = ResultBuilder<string, string>();

  if (!filePath.endsWith(".txt")) {
    return Err("Only .txt files are supported");
  }

  try {
    const fileContent = "File content"; // Simulated file read
    return Ok(fileContent);
  } catch (error) {
    return Err("Failed to process the file");
  }
}

Advantages

  • Eliminates Ambiguity: Clear distinction between success and error states.

  • Improves Readability: Declarative code that is self-documenting.

  • Avoids Exceptions: Promotes error handling via return types instead of exceptions.

  • Enhances Debugging: Easily identify and manage error cases.


API Reference

Result<A, E>

A generic class representing either a success (Ok) or failure (Err) value.

Methods:
  • is_ok(): Returns true if the result is Ok.

  • is_err(): Returns true if the result is Err.

  • ok(): Retrieves the success value.

  • err(): Retrieves the error value.

  • unwrap(): Returns the success value or throws an error if the result is Err.

  • unwrap_err(): Returns the error value or throws an error if the result is Ok.

Ok<A, E>

A subclass of Result representing a success state.

Err<E, A>

A subclass of Result representing an error state.

ResultBuilder

An interface for creating Ok and Err instances.

  • Ok<A, E>(value: A): Creates an Ok result with the given value.

  • Err<E, A>(error: E): Creates an Err result with the given error.


Contributing

Contributions are welcome! Open an issue or submit a pull request for bug fixes or enhancements.


License

This library is licensed under the MIT License. See LICENSE for details.


Keywords

TypeScript, Result, Rust, Functional Programming, Error Handling, Ok, Err, Library

Did you find this article valuable?

Support Michael Piper by becoming a sponsor. Any amount is appreciated!