/ts-elm

Elm types in TypeScript

Primary LanguageTypeScriptMIT LicenseMIT

ts-elm

Elm types in TypeScript

Implements Elm's Result type in TypeScript. Use it to make error handling explicit. Instead of throwing errors, you create Results with the ok and err functions.

Benefits

  • Type signatures indicate if a function can fail or not
  • Ensures that errors are always handled
  • Work with the data as if it always succeeds and add error handling where it makes the most sense
  • Fully typed
  • Zero dependencies

🔧 Example usage


📦 Install

npm install ts-elm

📰 API

The goal of the API is to be as similar to the original Elm code as possible.

There is purposefully no type guards to detect if a Result is Ok or Err. This is to force the use of match, which ensures that Errors are always handled.

Type and Constructors

type Result<Value, Error> = Ok<Value> | Err<Error>

A Result is either Ok meaning the computation succeeded, or it is an Err meaning that there was some failure.

Mapping

type map = ((x: any) => any, result: Result) => Result

Apply a function to a result. If the result is Ok, it will be converted. If the result is an Err, the same error value will propagate through.

Example:

map(Math.sqrt, ok(4)) // ok(2)
map(Math.sqrt, err('Bad input')) // err('Bad input')