TypeScript Monads

9.5.0 · active · verified Sun Apr 19

typescript-monads is a JavaScript/TypeScript library that provides common functional programming monads and abstractions to manage control flow and state, aiming to enable cleaner, safer code by reducing null/undefined checks and explicit error handling. It currently stands at version 9.5.0, with minor and patch releases occurring frequently (monthly to quarterly), and major versions released approximately yearly (v9.0.0 in January 2024). Key differentiators include its comprehensive set of monads like Maybe, List, Either, Result, State, and Reader, offering alternatives to traditional imperative logic for handling optional values, collections, error propagation, and side effects in a more declarative and type-safe manner within TypeScript projects. The library emphasizes lazy evaluation for collections and provides robust type definitions for seamless integration into TypeScript applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart illustrates the core usage of the Maybe, Result, and List monads for handling optional values, errors, and collections functionally. It demonstrates how to create instances, chain operations, and safely extract values or handle error conditions.

import { maybe, none, List, ok, fail } from 'typescript-monads';

// Demonstrating Maybe monad for optional values
function getUserDisplayName(user: { firstName?: string, lastName?: string }): string {
  return maybe(user.firstName)
    .flatMap(first => maybe(user.lastName).map(last => `${first} ${last}`))
    .valueOr('Guest');
}

console.log(getUserDisplayName({ firstName: 'Alice', lastName: 'Smith' }));
console.log(getUserDisplayName({ firstName: 'Bob' }));
console.log(getUserDisplayName({}));

// Demonstrating Result monad for error handling
function divide(a: number, b: number): typeof Result<number, string> {
  if (b === 0) {
    return fail('Cannot divide by zero');
  } 
  return ok(a / b);
}

divide(10, 2).match({
  ok: val => console.log(`Result: ${val}`), // Result: 5
  fail: err => console.error(`Error: ${err}`)
});

divide(10, 0).match({
  ok: val => console.log(`Result: ${val}`),
  fail: err => console.error(`Error: ${err}`)
}); // Error: Cannot divide by zero

// Demonstrating List monad for functional collections
const numbers = List.of(1, 2, 3, 4, 5);
const doubledEvens = numbers
  .filter(n => n % 2 === 0)
  .map(n => n * 2)
  .toArray();

console.log(doubledEvens); // [4, 8]

view raw JSON →