typescript-throws

1.0.1 • Public • Published

typescript-throws

A small utility class for Typescript to wrap throwable values as return types. This is very similar to Haskell maybe and either. It is also similar to Rust's Result and Option return types.

Coverage Build Version 1.01

Usage

To create a safe-by-design function, simply change your return type from <T> to Throws<T> and call Throws.pure(returnValue) on your return values. Finally, replace all throw new Error instances with Throws.pure(new Error).

class DivideByZeroError extends Error {
    constructor(message: string) {
        super(message);
        this.name = "DivideByZero"
    }
}
function divide(a: number, b: number): Throws<number> {
    if (b === 0) {
        return Throws.pure(new DivideByZeroError("Argument b is 0"));
    }
    return Throws.pure(a / b);
}

Opaque types

divide(5, 4) //  Throws: { "value": 1.25 }
divide(3, 0) //  Throws: { "value": { "name" : ... } }

Optional values

divide(5, 4).optional() // 1.25
divide(3, 0).optional() // null

Curried Bindings

// Curried
function divBy(b: number) {
    return (a: number) => divide(a, b)
}
divide(50,1).bind(divBy(2)).bind(divBy(2)).bind(divBy(.5)).optional() // 25
divide(50,0).bind(divBy(2)).bind(divBy(2)).bind(divBy(.5)).shouldThrow() // true
divide(50,0).bind(divBy(2)).bind(divBy(2)).bind(divBy(.5)).unwrap() // DivideByZeroError: Argument b is 0

Many-way Bindings

divide(5,4).bindMany(divide)(4).optional() // 0.3125
divide(5,0).bindMany(divide)(4).optional() // null

Dangerous Unwrap

divide(5, 4).unwrap() // 1.25
divide(3, 0).unwrap() // DivideByZeroError: Argument b is 0

Language

pure and bind come from the Haskell Standard Library Monad and Applicative interfaces.

Package Sidebar

Install

npm i typescript-throws

Weekly Downloads

4

Version

1.0.1

License

MIT

Unpacked Size

35.3 kB

Total Files

12

Last publish

Collaborators

  • omaribrahimdev