@spirex/result-type
v1.0.0
Published
Lightweight result monad for explicit, type-safe sync and async error handling.
Maintainers
Readme
@spirex/result-type
Lightweight, zero-dependency utility for safe and readable error handling in TypeScript and plain JavaScript.
Full types and JSDoc included. Use directly in TS projects with autocomplete and compile-time type safety. Works in plain JS runtime.
Designed for minimal bundle impact (0.8kb, ~0.4kb gzip)
Key Features
- Minimal API for success/failure results
- Typed success values and typed errors
- Safe accessors and functional helpers (map, or, ifOk, ifFail)
- Helpers to wrap promises and try/catch flows
- Works in pure JavaScript (with provided .d.ts for TypeScript)
When To Use
- Replace ad-hoc try/catch blocks with composable, typed results.
- Avoid throwing for control flow in critical flows.
- Improve readability of error handling without heavy libraries.
Installation
npm install @spirex/result-typeQuick Examples
Import package
import { Result } from '@spirex/result-type';Create Void Results
const okVoidResult = Result.ok();
const failVoidResult = Result.fail(new Error("Invalid operation"));Create Value Results
const okValueResult = Result.ok(42);
const failValueResult = Result.fail<Article>("Not found");Try-wrapper
const result = Result.try(() => JSON.parse('{}'));Access safely
// Throws if used on failure
if (okValueResult.ok) console.log(okValueResult.value)
// Safe accessor
console.log(okValueResult.safeValue ?? 0);Map & fallback
const mappedResult = okValueResult.map(n => String(n * 2));
// Returns value or default
const value = mapped.or(() => 10);Promises
// Wrap promise value into result
const wrapped = await Result.promise(fetchJson()); // Promise<IResultType<T>>
// Catch async errors
const attempt = await Result.try(async () => { await fetchConfiguration() });License
@spirex/result-type is released under the MIT License.
You are free to use, modify, and distribute the library in both personal and commercial projects.
