Skip to content

iyegoroff/ts-railway

Repository files navigation

ts-railway

npm build publish codecov Type Coverage Libraries.io dependency status for latest release bundlejs npm

ROP flavoured Result & AsyncResult types. Based on Railway oriented programming article by Scott Wlaschin.

Getting started

$ npm i ts-railway

Overview

Main types


Functions

All mapping functions have at least two overloaded signatures - common (transform, result) => new_result and curried (transform) => (result) => new_result. Curried form is intended to be used with some piping function (e.g. pipe-ts).

Result AsyncResult
success ↗️ 🚫
failure ↗️ 🚫
map ↗️ ↗️
mapError ↗️ ↗️
flatMap ↗️ ↗️
flatMapError ↗️ ↗️
mapAsync 🚫 ↗️
mapAsyncError 🚫 ↗️
match ↗️ ↗️
combine ↗️ ↗️

Usage

Avoiding 'pyramid of doom'

Composing several functions with multiple arguments can be cumbersome and will lead to 'pyramid of doom' style of code:

const div = (a: number, b: number) /*: Result<number, 'div by zero'> */ =>
  b === 0 ? Result.failure('div by zero' as const) : Result.success(a / b)

const result = Result.map(
  (x: string) => [...x].reverse().join(''),
  Result.map(
    (x: number) => `${x}`,
    Result.map(
      (x: number) => x + 234,
      Result.mapError(
        (x: 'div by zero') => ({ divError: x } as const),
        Result.map((x) => x * 2, div(500, 1))
      )
    )
  )
)

expect(result).toEqual({
  tag: 'success',
  success: '4321'
})

This can be easily avoided when using curried forms of functions with a piping function:

import { pipeWith } from 'pipe-ts'

const result = pipeWith(
  div(500, 1),
  Result.mapError((x) => ({ divError: x } as const)),
  Result.map((x) => x * 2),
  Result.map((x) => x + 234),
  Result.map((x) => `${x}`),
  Result.map((x) => [...x].reverse().join(''))
)

expect(result).toEqual<typeof result>({
  tag: 'success',
  success: '4321'
})

Programming style

There are certain catches of railway oriented programming. Most of them are matter of program design quality. But in the context of TypeScript language, the most serious problem is the ability to completely discard the result of a function call (TypeScript/#8240, TypeScript/#8584). For example, in the following snippet possible parsing error will be discarded:

declare const obj: {
  parse: <T>(json: string) => Result<T, Error>
}

function foo() {
  obj.parse('][') // Result is discarded!
}

foo()

More sneaky error:

declare function updateUser(info: { name: string }): AsyncResult<undefined, Error>

declare const MyButton: {
  onClick: () => void
}

MyButton.onClick(
  () => updateUser({ name: 'username' }) // AsyncResult is covered with void and discarded!
)

These kind of problems can be minimized by using proper project configuration: setting "strict": true in tsconfig, prohibiting expression statements with functional/no-expression-statement rule from eslint-plugin-functional and banning void type with @typescript-eslint/ban-types rule from @typescript-eslint/eslint-plugin. tsconfig.json and .eslintrc files from this project could be used as a starting point.


Exception handling

ts-railway is intended to handle only domain errors and doesn't catch thrown exceptions and unhandled promise rejections. The common scenario to deal with exceptions is to catch them globally, log somehow and then decide whether to prevent an exception by fixing/changing the program or to convert that exception to domain error:

const errorHandler: OnErrorEventHandlerNonNull = (event) => {
  MyLoggingService.log(event)
}

window.onerror = errorHandler
window.onunhandledrejection = errorHandler

'Ecosystem'

Some packages compatible with ts-railway:

  • spectypes - fast, compiled, eval-free data validator/transformer
  • fetchmap - non-throwing fetch wrapper
  • ts-elmish - elmish architecture in typescript