Registry / serialization / typescript-monads

typescript-monads

JSON →
library9.5.0jsnpmunverified

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.

npm install typescript-monads
INSTALL
IMPORT
SIG · TYPESCRIPT-MONADS
T
typescript-monads
serializationjavascriptv9.5.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

maybe
import { maybe } from 'typescript-monads'
const { maybe } = require('typescript-monads')
The library primarily targets modern JavaScript environments supporting ESM. While some bundlers might handle CJS `require`, direct usage in Node.js without transpilation should prefer ESM imports. `maybe` is the primary factory function for the Maybe monad.
List
import { List } from 'typescript-monads'
import List from 'typescript-monads'
List is a named export, not a default export. Incorrectly importing it as a default will result in `undefined`.
Result
import { Result } from 'typescript-monads'
import { result } from 'typescript-monads'
The `Result` monad itself is exported as a class (`Result`), while factory functions for success/failure are `ok` and `fail` (e.g., `import { ok, fail } from 'typescript-monads'`).
maybeToObservable
import { maybeToObservable } from 'typescript-monads'
Requires `rxjs` to be installed separately as an optional dependency. If `rxjs` is not present, calling this function will lead to a runtime error.

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]
Debug
Known issues
breakingThe signature of `Maybe.apply` method was changed in v9.0.0. Code using the `apply` method might need adjustments.
fix
Review the specific usage of `Maybe.apply` and update its arguments according to the new signature, as detailed in the v9.0.0 release notes or updated documentation.
affects: >=9.0.0
gotchaIntegration with RxJS features like `maybeToObservable` requires the `rxjs` package to be explicitly installed as a dependency in your project. It is not bundled with `typescript-monads`.
fix
Install RxJS: `npm install rxjs` or `yarn add rxjs`.
affects: >=1.0.0
gotchaAttempting to access a value from a `None` (for Maybe) or a `Fail` (for Result) directly without using safe methods like `valueOr`, `match`, or `tapSome`/`tapOk` will result in `undefined` or an unhandled value, negating the benefits of the monad.
fix
Always use provided monadic methods (e.g., `.valueOr(defaultValue)`, `.match({ some: ..., none: ... })`, `.flatMap(fn)`) to safely interact with values that may or may not be present, preventing unexpected runtime errors.
affects: >=1.0.0
gotchaThe library heavily relies on TypeScript type inference. While it provides runtime safety, incorrect type declarations when creating monads or using `flatMap`/`map` can lead to type mismatches that TypeScript might catch but could lead to logical errors if types are asserted incorrectly.
fix
Ensure strict TypeScript settings are enabled. Pay close attention to the generic types when instantiating monads (e.g., `none<number>()` or `List.empty<string>()`) and verify the return types of functions passed to `map`, `flatMap`, and `filter`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: (0, typescript_monads_1.maybeToObservable) is not a function
The `rxjs` package is not installed, but a function that integrates with RxJS (like `maybeToObservable`) is being called.
fix
Install RxJS as a dependency: `npm install rxjs` or `yarn add rxjs`.
TS2305: Module ''typescript-monads'' has no exported member 'result'.
Attempting to import `result` (lowercase) as a named export, but the primary factory functions are `ok` and `fail`, and the type is `Result` (uppercase).
fix
Use `import { ok, fail, Result } from 'typescript-monads'` instead. Factory functions are `ok()` and `fail()`, and the type is `Result<T, E>`.
ReferenceError: typescriptMonads is not defined (in browser)
The `typescript-monads` script was loaded directly in the browser via `unpkg` without ensuring it exposes a global variable, or it's trying to access `typescriptMonads` before the script fully loads or in a context where it's not exposed.
fix
Ensure the script is loaded and executed, and the correct global variable name is used. As per documentation, it exposes `typescriptMonads`. If using modern bundlers, prefer `import` statements.
TS2339: Property 'value' does not exist on type 'Maybe<number>' (or 'Result<string, Error>').
Directly trying to access a property like `.value` on a monad instance, which is an incorrect pattern as monads wrap values and require specific methods for safe extraction.
fix
Use the provided monadic methods for value extraction or transformation, such as `.valueOr(defaultValue)`, `.match(...)`, `.tapSome(...)`, `.map(...)`, or `.flatMap(...)`.
Upgrade
Version history
9.5.0latest on npm
Audit
Dependencies
rxjsoptionalRequired for `maybeToObservable` and other RxJS integration methods within the `Maybe` monad. It's an optional peer dependency.
Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources
typescript-monads — npm install typescript-monads · libregistry