npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

resultx

v2.0.2

Published

Minimalist, strongly-typed result pattern for TypeScript

Downloads

121

Readme

resultx

A lightweight and simple Result type for TypeScript, inspired by Rust's Result type.

Description

resultx provides a Result type that represents either success (Ok) or failure (Err). It helps to handle errors in a more explicit and type-safe way, without relying on exceptions.

For error handling in synchronous code, resultx provides a trySafe function that wraps a function that might throw an error. For asynchronous code, trySafe can also be used with promises.

Key Features

  • 🎭 Simple and intuitive Result type, wrapping Ok and Err values
  • 🚀 Supports both synchronous and asynchronous operations
  • 🛡️ Type-safe error handling
  • 🧰 Zero dependencies
  • 📦 Tiny bundle size (half a kilobyte minified)

Table of Contents

Installation

Add resultx to your dependencies by running one of the following commands, depending on your package manager:

pnpm add -D resultx

# Or with npm
npm install -D resultx

# Or with yarn
yarn add -D resultx

Usage

import { err, ok, trySafe, unwrap } from 'resultx'

// Create `Ok` and `Err` results
const successResult = ok(42)
//                    ^? Ok<number>
const failureResult = err('Something went wrong')
//                    ^? Err<"Something went wrong">

// Use `trySafe` for error handling
const result = trySafe(() => {
  // Your code that might throw an error
  return JSON.parse('{"foo":"bar"}')
})

// Either log the result or the error
if (result.ok) {
  console.log('Parsed JSON:', result.value)
}
else {
  console.error('Failed to parse JSON:', result.error)
}

// Or unwrap and destructure the result
const { value, error } = unwrap(result)

API

Result

The Result type represents either success (Ok) or failure (Err).

Type Definition:

type Result<T, E> = Ok<T> | Err<E>

Ok

The Ok type wraps a successful value.

Example:

const result = new Ok(42)

Type Definition:

declare class Ok<T> {
  readonly value: T
  readonly ok: true
  constructor(value: T)
}

Err

The Err type wraps an error value.

Example:

const result = new Err('Something went wrong')

Type Definition:

declare class Err<E> {
  readonly error: E
  readonly ok: false
  constructor(error: E)
}

ok

Shorthand function to create an Ok result. Use it to wrap a successful value.

Type Definition:

function ok<T>(value: T): Ok<T>

err

Shorthand function to create an Err result. Use it to wrap an error value.

Type Definition:

function err<E extends string = string>(err: E): Err<E>
function err<E = unknown>(err: E): Err<E>

trySafe

Wraps a function that might throw an error and returns a Result with the result of the function.

Type Definition:

function trySafe<T, E = unknown>(fn: () => T): Result<T, E>
function trySafe<T, E = unknown>(promise: Promise<T>): Promise<Result<T, E>>

unwrap

Unwraps a Result, Ok, or Err value and returns the value or error in an object. If the result is an Ok, the object contains the value and an undefined error. If the result is an Err, the object contains an undefined value and the error.

Example:

const result = trySafe(() => JSON.parse('{"foo":"bar"}'))
const { value, error } = unwrap(result)

Type Definition:

function unwrap<T>(result: Ok<T>): { value: T, error: undefined }
function unwrap<E>(result: Err<E>): { value: undefined, error: E }
function unwrap<T, E>(result: Result<T, E>): { value: T, error: undefined } | { value: undefined, error: E }

Examples

Basic Usage

A common use case for Result is error handling in functions that might fail. Here's an example of a function that divides two numbers and returns a Result:

import { err, ok } from 'resultx'

function divide(a: number, b: number) {
  if (b === 0) {
    return err('Division by zero')
  }
  return ok(a / b)
}

const result = divide(10, 2)
if (result.ok) {
  console.log('Result:', result.value)
}
else {
  console.error('Error:', result.error)
}

Error Handling with trySafe

The trySafe function is useful for error handling in synchronous code. It wraps a function that might throw an error and returns a Result:

import { trySafe } from 'resultx'

const result = trySafe(() => JSON.parse('{"foo":"bar"}'))

if (result.ok) {
  console.log('Parsed JSON:', result.value)
}
else {
  console.error('Failed to parse JSON:', result.error)
}

Async Operations with trySafe

For asynchronous operations, trySafe can also be used with promises. Here's an example of fetching data from an API:

import { trySafe } from 'resultx'

async function fetchData() {
  const result = await trySafe(fetch('https://api.example.com/data'))

  if (result.ok) {
    const data = await result.value.json()
    console.log('Fetched data:', data)
  }
  else {
    console.error('Failed to fetch data:', result.error)
  }
}

fetchData()

License

MIT License © 2023-PRESENT Johann Schopplich