attempt-ts
TypeScript icon, indicating that this package has built-in type declarations

3.0.2 • Public • Published

Attempt-TS


Build Status
Current NPM Version and Link   License   Documentation Link   TypeScript Link
code style: prettier   Semantic Release Link   Tested with Jest

Overview

Attempt-TS is a series of TypeScript helpers designed to make it easy and beautiful to define and read all types a function can both return and throw.

It is inspired in the common Maybe<T> pattern in TypeScript.

Quick Guide

This is a simple guide describing the most common use cases of Attempt-TS.

import { Attempt, Failure, Success }

// Attempts must return either Success() or Failure() and must not throw errors
const division = (a: number, b: number): Attempt<number,string> => {
  if (b === 0)
    return Failure("Can't divide by zero")
  return Success(a / b)
}

// Calling Attempt() on the result of an Attempt either returns the result or throws the error
Attempt(division(6,2)) // 3
Attempt(division(1,0)) // throws "Can't divide by zero"

// AsyncAttempt behave the same way but they're async
const asyncDivision = async (a: number, b: number): AsyncAttempt<number,string> => {
  if (b === 0)
    return Failure("Can't divide by zero")
  return Success(a / b)
}

// AsyncAttempt() also works the same way
await AsyncAttempt(asyncDivision(6,2)) // 3
await AsyncAttempt(asyncDivision(1,0)) // throws "Can't divide by zero"

Documentation

Documentation is available on https://gabs-simon.github.io/attempt-ts.

Documentation link

Readme

Keywords

Package Sidebar

Install

npm i attempt-ts

Weekly Downloads

83

Version

3.0.2

License

AGPL-3.0-or-later

Unpacked Size

710 kB

Total Files

111

Last publish

Collaborators

  • gabsimon