Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
A TypeScript implementation of the Option type, providing a robust way to handle nullable and optional values with enhanced type safety and functional patterns.
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
andundefined
, 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.
Add Package
deno add jsr:@oxi/option
Import symbol
import * as option from "@oxi/option";
Import directly with a jsr specifier
import * as option from "jsr:@oxi/option";
Add Package
pnpm i jsr:@oxi/option
pnpm dlx jsr add @oxi/option
Import symbol
import * as option from "@oxi/option";
Add Package
yarn add jsr:@oxi/option
yarn dlx jsr add @oxi/option
Import symbol
import * as option from "@oxi/option";
Add Package
vlt install jsr:@oxi/option
Import symbol
import * as option from "@oxi/option";
Add Package
npx jsr add @oxi/option
Import symbol
import * as option from "@oxi/option";
Add Package
bunx jsr add @oxi/option
Import symbol
import * as option from "@oxi/option";