@alt-stack/result
v0.1.4
Published
Type-safe Result type for explicit error handling inspired by Effect-TS
Maintainers
Readme
@alt-stack/result
Type-safe Result type for explicit error handling, inspired by Effect-TS.
Documentation
📚 Full documentation is available at: Result Documentation
Installation
pnpm add @alt-stack/result
# or
npm install @alt-stack/result
# or
yarn add @alt-stack/resultQuick Start
import { ok, err, isOk, isErr, TaggedError, type Result } from "@alt-stack/result";
// Define errors with _tag for exhaustive handling
class NotFoundError extends TaggedError {
readonly _tag = "NotFoundError";
constructor(public readonly id: string) {
super(`Resource ${id} not found`);
}
}
// Return Results instead of throwing
function getUser(id: string): Result<User, NotFoundError> {
const user = db.find(id);
if (!user) {
return err(new NotFoundError(id));
}
return ok(user);
}
// Handle results with type guards
const result = getUser("123");
if (isOk(result)) {
console.log(result.value.name);
} else {
console.log(result.error._tag); // "NotFoundError"
}Error Requirements
Errors must extend Error and have a _tag property with a string literal type:
// Option 1: Extend TaggedError (recommended)
class ValidationError extends TaggedError {
readonly _tag = "ValidationError";
constructor(public readonly field: string) {
super(`Invalid field: ${field}`);
}
}
// Option 2: Extend Error directly
class DatabaseError extends Error {
readonly _tag = "DatabaseError" as const;
constructor(message: string) {
super(message);
this.name = "DatabaseError";
}
}Exhaustive Error Handling
The _tag property enables exhaustive switch statements:
type UserError = NotFoundError | ValidationError | DatabaseError;
function handleError(error: UserError): string {
switch (error._tag) {
case "NotFoundError":
return `User ${error.id} not found`;
case "ValidationError":
return `Invalid: ${error.field}`;
case "DatabaseError":
return `Database error: ${error.message}`;
// TypeScript ensures all cases are handled
}
}API Reference
Core Types
Result<A, E>- Discriminated union ofOk<A>orErr<E>Ok<A>- Success case withvalue: AErr<E>- Error case witherror: EResultError- Type constraint:Error & { readonly _tag: string }TaggedError- Base class that setsnamefrom_tag
Constructors
ok(value?)- Create success Result (supports void)err(error)- Create error Result
Type Guards
isOk(result)- Narrow toOk<A>isErr(result)- Narrow toErr<E>
Transformations
map(result, fn)- Transform success valueflatMap(result, fn)- Chain Result-returning functionsmapError(result, fn)- Transform error valuecatchError(result, fn)- Recover from errors
Extraction
unwrap(result)- Get value or throwunwrapOr(result, default)- Get value or defaultunwrapOrElse(result, fn)- Get value or compute defaultgetOrUndefined(result)- Get value or undefinedgetErrorOrUndefined(result)- Get error or undefined
Pattern Matching
match(result, { ok, err })- Handle both casesfold(result, onErr, onOk)- Reduce to single value
Async Utilities
ResultAsync<A, E>- Type alias forPromise<Result<A, E>>fromPromise(promise, onReject)- Wrap promise in ResulttryCatch(fn, onError)- Wrap sync functiontryCatchAsync(fn, onError)- Wrap async function
Combinators
all(results)- Combine Results (fail-fast)firstOk(results)- Find first successtap(result, fn)- Side effect on successtapError(result, fn)- Side effect on errorResultAggregateError- Aggregates multiple errors
Type Inference
InferErrorTag<E>- Extract_tagliteral typeInferErrorTags<E>- Extract all_tagvalues from unionNarrowError<E, Tag>- Narrow error union by tagisResultError(error)- Runtime check for ResultErrorassertResultError(error)- Runtime assertion
Framework Integration
The Result type is used throughout Altstack packages. Server, Kafka, and Workers packages re-export Result utilities:
// Import from framework package
import { ok, err, isOk, isErr } from "@alt-stack/server-hono";
// Or import directly
import { ok, err, isOk, isErr } from "@alt-stack/result";Related Packages
@alt-stack/server-hono- Type-safe HTTP server@alt-stack/server-express- Express adapter@alt-stack/workers-core- Background workers
License
MIT
