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

ts-railway

v6.1.4

Published

ROP flavoured Result & AsyncResult types

Downloads

757

Readme

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