This TypeScript library provides two main types, Optional and Attempt, for handling values that may or may not exist (Optional
) and operations that may either succeed or fail (Attempt
). It aims to make code more expressive and handle edge cases effectively, reducing the risk of runtime errors.
The Optional
type encapsulates a value that may or may not be present, similar to "Option" or "Maybe" types in functional programming languages. It provides methods for safely accessing, transforming, and handling values, including map
, flatMap
, filter
, orEval
, and more.
Optional.some(value)
- Wraps a value in a Some instance, representing an existing value.
Optional.none()
- Creates a None instance, representing an absent value.
Optional.ofNullable(value)
- Wraps a potentially nullable value, returning Some if the value is non-null, or None otherwise.
Other utilities like find
, findIndex
, indexOf
, lastIndexOf
, and firstOf
make it easy to work with arrays in a functional style.
The Attempt
type encapsulates the result of an operation that may succeed or fail. Similar to "Result" types in other languages, Attempt
allows you to handle errors in a streamlined, functional way without relying on exceptions.
Attempt.ok(value)
- Creates an Ok instance, representing a successful operation.
Attempt.err(error)
- Creates an Err instance, representing a failure with an associated error.
Attempt.tryEval(callback)
- Executes a callback, wrapping its result in Ok if successful, or Err if an exception is thrown.
Install the library via npm:
npm install unexceptable
Use Optional
to wrap values that may or may not exist. Here are some examples:
import {Optional} from "unexceptable";
const value = Optional.some("foo");
const noValue = Optional.none();
console.assert(value.map(value => value.toUpperCase()).orThrow() === "FOO");
console.assert(noValue.orValue(42) === 42);
import {Optional} from "unexceptable";
interface BackendConfig {
host: Optional<string>;
port: Optional<number>;
baseHref: Optional<string>;
}
function getBackendUrl(config: BackendConfig) {
const host = config.host.orValue("localhost");
const port = config.port.orValue(443);
if (config.baseHref.isSome()) {
return `${host}:${port}/${config.baseHref.value}`;
} else {
return `${host}:${port}`;
}
}
Use Attempt
for operations that may succeed or fail. This lets you handle errors more gracefully without try/catch blocks:
import {Attempt} from "unexceptable";
const success = Attempt.ok(42);
const failure = Attempt.err("Something went wrong");
console.assert(success.map(value => value + 27).orValue(420) === 69);
console.assert(failure.orValue(1337) === 1337);
import {Attempt} from "unexceptable";
import {Settings} from "./some/dir";
function loadSettings(): Attempt<Settings, Error> {
const entry = localStorage.getItem("settings");
if (entry === null) {
return Attempt.err(Error("No settings in local storage yet."));
}
return Attempt
.tryEval(() => JSON.parse(entry))
.mapErr(err => new Error("Failed to parse settings.", err));
}
Contributions are welcome! Please open an issue or submit a pull request if you'd like to help improve this library.
This library is open-source and available under the MIT License.