@eriveltondasilva/option.js
v1.0.3
Published
A lightweight, type-safe library inspired by Rust's `Option` enum for handling optional values in JavaScript and TypeScript without `null` or `undefined` pitfalls.
Downloads
430
Maintainers
Readme
Option.js
A lightweight, type-safe library inspired by Rust's Option enum for handling optional values in JavaScript and TypeScript without null or undefined pitfalls.
Features
- Type-safe by design: Eliminates unsafe
null/undefinedaccess by enforcing explicit handling. - Composable API: Chainable methods like
map,andThen,filter,unwrapOr, and more. - Singleton
NONE: Single shared instance for better memory usage. - TypeScript-first: Fully typed with excellent inference.
- Tiny footprint: Zero dependencies and minimal bundle size.
Installation
npm install @eriveltondasilva/option.jsbun add @eriveltondasilva/option.jsImport
// Recommended
import { Option } from '@eriveltondasilva/option.js'
// Default Import
import Option from '@eriveltondasilva/option.js'
// Named Helpers - shortcuts for Option.some() and Option.none()
import { some, none } from '@eriveltondasilva/option.js'
// Types
import type { Option, AsyncOption, Some, None } from '@eriveltondasilva/option.js'Usage
Basic Example
function getUsername(id: number): Option<string> {
const users = { 1: 'Erivelton' }
return Option.fromNullable(users[id])
}
const user = getUsername(1)
.map((name) => name.toUpperCase())
.unwrapOr('ANONYMOUS')
console.log(user)
// => log "ERIVELTON"Chaining with and() and andThen()
const some = Option.some(10)
const other = Option.some(20)
// Returns 'other' only if 'some' is Some
const result = some.and(other)
// Chain operations that return Options
const result = some.andThen((val) => Option.some(val * 2))Pattern Matching
const result = Option.fromNullable(someData)
const message = result.match({
some: (val) => `Found: ${val}`,
none: () => 'Nothing here',
})API Overview
Factories
Option.some(val): Wraps a value.Option.none(): The singleton instance for absent values.Option.fromTry(fn): Creates an Option from a function that may throw.Option.fromNullable(val): Safely convertsnull|undefinedtoNone.
Guards
Option.isOption(val): Checks if a value is an instance ofSomeorNone.Option.isSome(val): Type guard forSome.Option.isNone(val): Type guard forNone.
Key Instance Methods
| Method | Description |
| :----------------- | :-------------------------------------------------- |
| .map(fn) | Transforms the value inside a Some. |
| .and(other) | Returns other if instance is Some, else None. |
| .andThen(fn) | Returns the Option resulting from fn if Some. |
| .unwrapOr(alt) | Returns value or the provided fallback. |
| .match(handlers) | Executes a branch based on the state. |
| .inspect(fn) | Runs a side-effect without changing the Option. |
License
MIT © Erivelton Silva
Related Projects
If you find this library useful, check out my other functional utilities:
@eriveltondasilva/result.js — A type-safe way to handle errors and successes without try/catch overhead, inspired by Rust's Result type.
import { Option } from '@eriveltondasilva/option.js'
import { Result } from '@eriveltondasilva/result.js'
const user = Option.fromNullable(null) // => None
// Converting an Option to a Result (conceptually)
const userResult = user.match({
some: (val) => Result.ok(val),
none: () => Result.err('User not found'),
})
// => Err("User not found")