Skip to content

eriveltondasilva/result.js

Repository files navigation

Result.js — Rust-inspired Result Type

result.js Node TypeScript Zero Dependencies Size License: MIT

Result.js

Available in: Português | Español

A lightweight, Rust-inspired Result type for Javascript and Typescript. Handle success and error cases explicitly without exceptions.

Features

  • 🦀 Rust-inspired API - Familiar Result<T, E> pattern
  • 🎯 Type-safe - Full Typescript support with excellent inference
  • 📦 Zero dependencies - Lightweight and focused
  • 🔗 Chainable - Fluent API with map, andThen, and more
  • Tree-shakeable - Optimized bundle size
  • 🛡 No exceptions - Safe error handling without try-catch

Quick Start

Installation

npm install @eriveltonsilva/result.js

Import

// ES6 - Recommended
import { Result } from '@eriveltonsilva/result.js'

// ES6 - Default Import
import Result from '@eriveltonsilva/result.js'

// CommonJS
const { Result } = require('@eriveltonsilva/result.js')

Basic Usage

// Create Results
const success = Result.ok(42)
const failure = Result.err(new Error('Something went wrong'))

// Check and unwrap
if (success.isOk()) {
  console.log(success.unwrap()) // 42
}

// Chain operations
const doubled = Result.ok(21)
  .map((x) => x * 2)
  .andThen((x) => Result.ok(x + 10))
  .unwrap() // 52

// Pattern matching
const result = Result.ok(42)
  .match({
    ok: (value) => value * 2,
    err: (error) => error.message,
  }) // 84

// Handle errors safely
const result = Result.fromTry(
  () => JSON.parse('invalid'),
  (error) => new Error(`Invalid JSON: ${error}`)
) // Error: Invalid JSON: SyntaxError: Unexpected token, "invalid" is not valid JSON

Documentation

For comprehensive guides, API reference, and advanced usage patterns, see the complete documentation.

Learn more:

Changelog

See CHANGELOG.md for a detailed list of changes in each release.

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

MIT © Erivelton Silva

Inspiration

Inspired by:

About

A lightweight, Rust-inspired Result type for JavaScript and TypeScript — handle success and error cases without exceptions.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors