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

@haideralsh/ts-result

v0.1.2

Published

A zero-dependency Result type for typescript inspired by Rust

Downloads

11

Readme

ts-result logo

ts-result

A zero-dependency Result type for TypeScript inspired by Rust

Install

$ npm install @haideralsh/ts-result

Usage

Example adapted from the Elm guide

import { Result, Ok, Err } from '@haideralsh/ts-result'

function isReasonableAge(age: number): Result<number, string> {
    if (age < 0) return Err('Please try again after you are born.')
    if (age > 135) return Err('Are you some kind of a turtle?')

    return Ok(age)
}

const ageResult = isReasonableAge(9000)

if (ageResult.ok === true) {
    const age = ageResult.get()
} else {
    console.error(ageResult.getError()) // Are you some kind of a turtle?
}

What is a Result type and why should I use it?

A Result type is the result of a computation that may fail. The type is used for returning and propagating errors. It is helpful to give additional information when things go wrong.

Example

Let us say that we want to insert a user into our database and return the user entity back:

function addUser(name: string, email: string): User {
    const { uuid } = db.query('insert into user values (?, ?)', name, email)
    return User.getById(uuid)
}

However, an insertion operation can sometimes fail. There is no way for the caller of the function above to know that such failure could happen without diving into the implementation of the function.

We could handle the potential failure ourselves and return nothing when the failure happens:

function addUser(name: string, email: string): User | null {
    try {
        const { uuid } = db.query('insert into user values (?, ?)', name, email)
        return User.getById(uuid)
    } catch (err) {
        return null
    }
}

If TypeScript is configured properly, this could be an improvement since TypeScript will warn the caller that the result may be null. However, it doesn't provide them a way to know what is the error that occurred.

We can change the null to be a string instead:

function addUser(name: string, email: string): User | string {
    try {
        const { uuid } = db.query('insert into user values (?, ?)', name, email)
        return User.getById(uuid)
    } catch (err) {
        return err.message
    }
}

This is not any better because now we lose the TypeScript null warning and we still have to check if the returned type is a string or a User which can be non-trivial.

This problem becomes more pronounced when both the okay and error results share the same type. Let us say we only want to return the user identifier instead of the whole User object:

function addUser(name: string, email: string): string {
    try {
        const { uuid } = db.query('insert into user values (?, ?)', name, email)
        return uuid
    } catch (err) {
        return err.message
    }
}

Now we can not tell if the string returned is the user's UUID or the error message.

This is where the Result type comes in. It provides a more elegant way for handling potentially erroneous results.

We can rewrite the above example into this:

import { Result, Ok, Err } from '@haideralsh/ts-result'

function addUser(name: string, email: string): Result<string, string> {
    try {
        const { uuid } = db.query('insert into user values (?, ?)', name, email)
        return Ok(uuid)
    } catch (err) {
        return Err(err.message)
    }
}

Now the caller of this function can use the ok property to know which type of result is returned

const insertResult = addUser('Micheal', '[email protected]')

if (insertResult.ok === true) {
    const userId = insertResult.get() // The user's UUID if the insertion succeeded
} else {
    const errorMsg = insertResult.getError() // The error message if the insertion failed
}

API

Result<T, E>

A Result type accepts two generics. The first (T) must match the value type passed to Ok, while the second (E) must match the value type passed to Err.

A function with a return type Result must return either an Ok or Err or both of them matching their respective types.

import { Result, Ok, Err } from '@haideralsh/ts-result'

function divide(a: number, b: number): Result<number, string> {
    if (b === 0) {
        return Err('Division by zero!')
    }

    return Ok(a / b)
}

Properties and functions on a result wrapped with Ok or Err:

We can use the ok property in order to know if the result was wrapped with an Ok or an Err

ok: boolean

The property ok will be true if a result was wrapped with an Ok or false if it was wrapped with Err.

// See `divide` implementation above
const divideResult = divide(1, 1)

console.log(divideResult.ok) // true
// See `divide` implementation above
const divideResult = divide(1, 0)

console.log(divideResult.ok) // false

getOr(defaultValue: any): any

The getOr function will return the ok value if the result was wrapped with an Ok or the supplied default value if it was wrapped with Err.

// See `divide` implementation above
const divideResult = divide(1, 1)

console.log(divideResult.getOr('foo')) // 1
// See `divide` implementation above
const divideResult = divide(1, 0)

console.log(divideResult.getOr('foo')) // foo

getOrThrow(err?: Error | string): any

The getOrThrow function will return the ok value if the result was wrapped with an Ok or throw an error using the Err value as a message. You can supply the error or the error message to throw as an optional parameter.

// See `divide` implementation above
const divideResult = divide(1, 1)

console.log(divideResult.getOrThrow('foo')) // 1
// See `divide` implementation above
const divideResult = divide(1, 0)

console.log(divideResult.getOrThrow()) // Uncaught Error: Division by zero!
console.log(divideResult.getOrThrow('foo')) // Uncaught Error: foo
console.log(divideResult.getOrThrow(new MyCustomError('foo'))) // Uncaught MyCustomError: foo

getOrRun: <S>(fn: () => S): any

The getOrRun function will return the ok value if the result was wrapped with an Ok or run a function if the result was wrapped with an Err.

// See `divide` implementation above
const divideResult = divide(1, 1)

function greeting() {
    return 'Hello world!'
}

console.log(divideResult.getOrRun(greeting)) // 1
// See `divide` implementation above
const divideResult = divide(1, 0)

function greeting() {
    return 'Hello world!'
}

console.log(divideResult.getOrRun(greeting)) // Hello world!

mapWithDefault<S, R>(defaultValue: S, fn: (parameter: any) => R): R

The mapWithDefault function will apply a function on the ok value if the result was wrapped with an Ok or the error value if the result was wrapped with an Err. The return type will be the same as the supplied function to map.

// See `divide` implementation above
const divideResult = divide(1, 1)

function addOne(num: number) {
    return num + 1
}

console.log(divideResult.mapWithDefault(10, addOne)) // 2
// See `divide` implementation above
const divideResult = divide(1, 0)

function addOne(num: number) {
    return num + 1
}

console.log(divideResult.mapWithDefault(10, addOne)) // 11

Ok(value: T)

The Ok function accepts a value of type T that must match the T generic type passed to Result<T, E>

Properties and functions unique to a result wrapped with an Ok function:

get(): T

The get function will unwrap the value wrapped with an Ok. You have to check if the ok property is true first before being able to use get.

const okResult = OK('foo')

if (okResult.ok === true) console.log(okResult.get()) // foo

map: <S>(fn: (parameter: T) => S): S

The map function will unwrap and apply the supplied function on the value wrapped with an Ok. The supplied function must accept the same type as the wrapped value type. The return type of the map function will be the same as the one of the supplied function. You have to check if the ok property is true first before being able to use map.

const okResult = OK('foo')

function capitalize(str: string) {
    return str.toUpperCase()
}

if (okResult.ok === true) console.log(okResult.map(capitalize)) // FOO

Err(errorValue: E)

The Err function accepts a value of type E that must match the E generic type passed to Result<T, E>

Properties and functions unique to a result wrapped with an Err function:

getError(): E

The getError function will unwrap the value wrapped with an Err. You have to check if the ok property is false first before being able to use getError.

const errResult = Err('foo')

if (errResult.ok === false) console.log(errResult.getError()) // foo