@team23/ts-result
TypeScript icon, indicating that this package has built-in type declarations

0.1.8 • Public • Published

Table of contents

Introduction

ts-result is a collection of utilities to better handle errors in TypeScript on the basis of a type-safe wrapper object. It also contains some Rxjs operators to simplify the handling in a reactive environment.

Core Concept

The core concept behind ts-result is that it's not possible to define all possible error results of a JavaScript/TypeScript function, which can lead to repeated error handling code when the function's return value is processed.

ts-results wraps the result value of functions in an object containing either the desired data value (which may be undefined for void functions) or an error value (which can be anything that helps you pass valuable error information), without requiring or triggering any exception handling code.

In every use of that function you will now get information about expected errors from that function.

Installation

Requirements

  • TypeScript +5.0
  • Rxjs +7.8

Using npm

npm i @team23/ts-result

Basic usage

Wrap your function return value inside the Result object and define possible error outcomes. The Error is an object containing an optional Message and a generic key (which can be defined at will)

function divide(dividend: number, divisor: number): Result<number, DividedByZeroError> {
    if (divisor === 0) {
        return {
            error: { key: new DividedByZeroError(), message: 'Cannot devide by 0!' },
        };
    }

    return { data: dividend / divisor };
}

You now do have information about possible errors in other functions and can process them accordingly

function main(x: number, y: number): void {
    const quotient = divide(x, y);

    if (quotient.data) {
        // quotient.data -> number
    }

    if (quotient.error) {
        // quotient.error.key -> DividedByZeroError
    }
}

Types

Other than the Result type, the library defines these helper types:

DataResult                                  // A Result that contains a data value
ErrorResult                                 // A Result that contains an error value
ErrorTypeOfResult<r>                        // Where r is a Result, this is the type of its error value
ErrorTypeOfResultObservable<r>              // Where r is an Observable<Result>, this is the type of its error value
ErrorTypeOfFunction<typeof f>               // Where f is a function that returns Observable<Result>, this is the type of its error value

TypeGuards

There are two typeguards provided to ease the error handling later on

import { isErrorResult } from './is-result';

const result: Result<number, Error>;

if (isDataResult(result)) {
    // data case - result.data is defined
    // (Because the data value is allowed to be undefined, this is the case when the object has a data property and does not contain an error value.)
}

if (isErrorResult(result)) {
    // error case - result.error is defined
}

Utilities

There are some factories provided to ease the creation of result objects

ToResult.fromData(value)        // Returning value as DataResult { data: value }
ToResult.fromErrorKey(value)    // Returning value as ErrorResult { error: { key: value } }
ToResult.fromData$(value)       // Returning value as Observable<{ data: value }>
ToResult.fromErrorKey$(value)   // Returning value as Observable<{ error: { key: value } }>
ToResult.fromResultArray(value) // Collating an array of results into one result, i.e. Array<Result<T, E>> to Result<Array<T>, E>

Operators

toDataResult

The toDataResult operator wraps the source value in a DataResult, with the source value becoming the data value.

source$.pipe(
    // 1
    toDataResult(),
    // { data: 1 }
)

toErrorResult

The toErrorResult operator wraps the source value in an ErrorResult, with the source value becoming the error key. An error message can be optionally added.

source$.pipe(
    // { status: 404 } }
    toErrorResult('Failed to connect.'),
    // { error: { key: { status: 404 }, message: 'Failed to connect.' } }
)

tapResult

The tapResult operator provides an easy way to hande side effects based on the function result

source$.pipe(
    tapResult({ 
        data: sideEffectOnDataCase,
        error: sideEffectOnErrorCase
    }),
)

pipeDataResult

The pipeDataResult defines a new rxjs pipe that is only run when the incoming value is identified as a DataResult. It can take up to nine rxjs operators and allows transforming the data, but must return a Result in the end (may be an ErrorResult or a differently typed DataResult).

source$.pipe(
    pipeDataResult(
        map(result => transformData(result.data)),
        toDataResult(),
    ),
)

pipeErrorResult

The pipeErrorResult defines a new rxjs pipe that is only run when the incoming value is identified as an ErrorResult. It can take up to nine rxjs operators and allows transforming the data, but must return a Result in the end (may be a differently typed ErrorResult or a DataResult).

source$.pipe(
    pipeErrorResult(
        switchMap(alternativeRequest$),
    ),
)

dataResultOr

The dataResultOr operator allows easily preparing an alternative value that should be used if the incoming value is not a DataResult. May return a differently typed DataResult than the source value.

source$.pipe(
    dataResultOr(0),
    // Will return either the desired result or DataResult<number>
)

invertResultArray

When combining multiple sources, you may end up with an Array of Result values. The invertResultArray operator automatically flips this Array to a Result containing an Array of the respective data values. If any of the Result values is errored, the returned Result is an ErrorResult with the first found error.

source$.pipe(
    // [{ data: 0 }, { data: 1 }, { data: 2 }]
    invertResultArray(),
    // {data: [0, 1, 2]}
)

source$.pipe(
    // [{ data: 0 }, { error: { key: 'Error A' } }, { error: 'Error B' }]
    invertResultArray(),
    // {error: { key: 'Error A'}}}
)

Changelog

View the changelog at CHANGELOG.md

/@team23/ts-result/

    Package Sidebar

    Install

    npm i @team23/ts-result

    Weekly Downloads

    55

    Version

    0.1.8

    License

    MIT

    Unpacked Size

    61.5 kB

    Total Files

    45

    Last publish

    Collaborators

    • tazlog
    • laura_schmid
    • schroeter
    • brandt-team23
    • goester-team23
    • ademeter