Skip to main content

@oxi/option@0.2.0

A TypeScript implementation of the Option type, providing a robust way to handle nullable and optional values with enhanced type safety and functional patterns.

Works with
This package works with Bun
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Browsers
JSR Score
100%
Published
2 months ago (0.2.0)

The Option module provides a TypeScript implementation of the Option type, inspired by Rust's Option enum. This utility is designed for scenarios where a value may or may not be present, allowing for safer and more expressive handling of such cases compared to using null or undefined. The Option type encapsulates the presence (Some) or absence (None) of a value, providing a rich API for interacting with these states.

Features

  • Some: Represents the presence of a value.
  • None: Represents the absence of a value.
  • Safety: Avoids the pitfalls of null and undefined, providing a safer alternative.
  • Functional: Offers a functional approach to handling optional values, including map, filter, and fold operations.

Usage Examples

Creating an Option

import { Option } from './Option';

// Create an Option with a value
const someValue = Option.Some(42);

// Create an Option with no value
const noValue = Option.None;

Working with an Option

// Unwrapping a value with a default
const value = Option.Some(42).unwrapOr(100); // Returns 42
const defaultValue = Option.None.unwrapOr(100); // Returns 100

// Mapping an Option
const stringValue = Option.Some(42).map(value => value.toString()); // Option.Some("42")
const noValueMap = Option.None.map(value => value.toString()); // Option.None

// Using match for branching logic
const matchExample = Option.Some(42).match(
  value => `Value is ${value}`,
  () => 'No value'
); // "Value is 42"
const matchNoneExample = Option.None.match(
  value => `Value is ${value}`,
  () => 'No value'
); // "No value"

These examples illustrate basic usage of the Option type. The Option class provides a robust API for more complex scenarios, enabling more expressive and safer code.

Built and signed on
GitHub Actions
View transparency log

Add Package

deno add @oxi/option

Import symbol

import * as mod from "@oxi/option";

Add Package

npx jsr add @oxi/option

Import symbol

import * as mod from "@oxi/option";

Add Package

yarn dlx jsr add @oxi/option

Import symbol

import * as mod from "@oxi/option";

Add Package

pnpm dlx jsr add @oxi/option

Import symbol

import * as mod from "@oxi/option";

Add Package

bunx jsr add @oxi/option

Import symbol

import * as mod from "@oxi/option";