ts-results: Rust-like Result and Option for TypeScript

3.3.0 · maintenance · verified Tue Apr 21

ts-results is a TypeScript library that provides compile-time error checking and optional values, inspired by Rust's `Result` and `Option` enums. It offers a type-safe approach to handling fallible operations and potential absence of values without relying on exceptions or `null`/`undefined`. The current stable version, 3.3.0, was last published in 2021. This package differentiates itself by offering a lightweight, focused implementation of these core algebraic data types, in contrast to more comprehensive functional programming libraries. It enables developers to explicitly model success (`Ok`) or failure (`Err`) states and presence (`Some`) or absence (`None`) of a value, leveraging TypeScript's type system to ensure these states are handled at compile time, thereby reducing runtime errors.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `Result` for explicit error handling in a file read operation and `Option` for handling potentially missing user configuration values, ensuring type safety at compile time.

import { Ok, Err, Result, Some, None, Option } from 'ts-results';
import { readFileSync, existsSync } from 'fs';

// --- Result Example: Handling file operations ---

function readFileSafe(path: string): Result<string, 'file_not_found' | 'read_error'> {
  if (!existsSync(path)) {
    return new Err('file_not_found');
  }
  try {
    const content = readFileSync(path, 'utf8');
    return new Ok(content);
  } catch (e) {
    return new Err('read_error');
  }
}

const filePath = 'test.txt';
// Simulate creating a file for the example
require('fs').writeFileSync(filePath, 'Hello, ts-results world!');

const fileResult = readFileSafe(filePath);

if (fileResult.ok) {
  console.log(`File content: ${fileResult.val}`);
} else {
  console.error(`Error reading file: ${fileResult.val}`);
}

// --- Option Example: Handling potentially missing configuration ---

interface UserConfig {
  theme?: string;
  notificationsEnabled?: boolean;
}

function getUserTheme(config: UserConfig): Option<string> {
  if (config.theme) {
    return new Some(config.theme);
  } else {
    return None;
  }
}

const userSettings: UserConfig = { notificationsEnabled: true };
const themeOption = getUserTheme(userSettings);

if (themeOption.some) {
  console.log(`User theme: ${themeOption.val}`);
} else {
  console.log('User theme not set, using default.');
}

// Clean up simulated file
require('fs').unlinkSync(filePath);

view raw JSON →