TypeScript’s fp-ts for n00bs

Originally posted on 2022-12-28

TypeScript is not my daily driver language. If it isn’t yours either, and you’re coming from a language that has constructs like Either, Option, etc. then you’re in luck. This is my cheat sheet to using these constructs in TypeScript.

Using Option to return errors


  • The validation function doesn’t throw the error itself so the caller can recover on their own
  • The validation function can return a descriptive error message that can be optionally presented to the user if it is unrecoverable
  • Errors can be handled without adding additional nesting

Step 1: Import map, none, some, and pipe

import {map, none, some} from "fp-ts/Option";
import {pipe} from "fp-ts/function";

Step 2: Do something that could raise an error

function isUsable(num): Option<Error> {
  if (num < 0) return some(new Error("We cannot use numbers less than zero"))
  return none

Step 3: Deal with that error later

let errorOption = isUsable(1234)

// Throw any errors
pipe(errorOption, map(error => { throw error }))