Option Type for JavaScript

0.2.4 · abandoned · verified Sun Apr 19

This package provides a robust implementation of the option (or maybe) type for JavaScript, designed to manage optional values and mitigate the pervasive issues of `null` and `undefined`. It offers a functional approach to handling the presence or absence of a value through `some(value)` and `none` constructs, similar to types found in languages like Rust or Scala. The current stable version is `0.2.4`, which was published approximately nine years ago, indicating that the package is no longer actively maintained. Key differentiators include its rich API for value manipulation, such as `map`, `flatMap`, `filter`, `orElse`, and `valueOrElse`, which promote safer and more expressive code compared to traditional null checks. Its `fromNullable` function also provides a convenient way to convert potentially nullish values into `option` types.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating 'some' and 'none' options, performing checks, safely unwrapping values with `valueOrElse`, and using `fromNullable`.

const option = require("option");

// Creating Option instances
const someUser = option.some({
    id: 1,
    name: () => "Alice"
});
const noUser = option.none;

// Basic checks
console.log(`someUser isSome: ${someUser.isSome()}`); // true
console.log(`noUser isNone: ${noUser.isNone()}`);     // true

// Retrieving values safely
function greet(userOption) {
    return userOption.map(user => user.name())
                     .valueOrElse("Anonymous");
}

console.log(`Greeting someUser: Hello ${greet(someUser)}`); // Hello Alice
console.log(`Greeting noUser: Hello ${greet(noUser)}`);     // Hello Anonymous

// Using fromNullable
const nullableString = Math.random() > 0.5 ? "A string" : null;
const safeOption = option.fromNullable(nullableString);
console.log(`From nullable: ${safeOption.valueOrElse("No string provided")}`);

view raw JSON →