ROP flavoured Result & AsyncResult types
npm install ts-railway




!Libraries.io dependency status for latest release


ROP flavoured Result & AsyncResult types. Based on Railway oriented programming article by Scott Wlaschin.
$ npm i ts-railway
- SuccessResult - represents a success with an associated value of Success type
- FailureResult - represents a failure with an associated value of Failure type
- Result - a union of SuccessResult and FailureResult
- AsyncResult - a Result wrapped in Promise
- SomeResult - a union of Result and AsyncResult
---
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 | ↗️ | ↗️ |
---
Composing several functions with multiple arguments can be cumbersome and will lead to 'pyramid of doom' style of code:
``typescript
const div = (a: number, b: number) /: Result
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:
`typescript
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
tag: 'success',
success: '4321'
})
`
---
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:
`typescript
declare const obj: {
parse:
}
function foo() {
obj.parse(']') // Result is discarded!
}
foo()
`
More sneaky error:
`typescript
declare function updateUser(info: { name: string }): AsyncResult
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,functional/no-expression-statement
prohibiting expression statements with 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.
---
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:
`typescript
const errorHandler: OnErrorEventHandlerNonNull = (event) => {
MyLoggingService.log(event)
}
window.onerror = errorHandler
window.onunhandledrejection = errorHandler
`
---
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