Skip to main content
Home
This package has been archived, and as such it is read-only.

Built and signed on GitHub Actions

latest

A small, focused TypeScript library for safer code through functional patterns using natural language. Inspired by folktale.

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
100%
Published
a month ago (0.5.0)
class Result

Represents the result of a computation that may fail.

Result is a functional approach to error handling that makes success and failure explicit in the type system. Instead of throwing exceptions, operations return a Result that is either Ok (success) or Error (failure).

This pattern forces callers to handle both success and error cases, making error handling more predictable and easier to reason about.

Examples

Example 1

// Basic usage
function divide(a: number, b: number): Result<number> {
  if (b === 0) {
    return Result.Error('Cannot divide by zero')
  }
  return Result.Ok(a / b)
}

const result = divide(10, 2)
result.matchWith({
  Ok: (value) => console.log(`Result: ${value}`),
  Error: (error) => console.error(`Error: ${error}`)
})

Example 2

// Wrapping throwing code
const result = Result.Try(() => JSON.parse(input))

Example 3

// Wrapping promises
const result = await Result.FromPromise(fetch('/api/data'))

Constructors

new
Result(
success: boolean,
value: Type,
error: ResultError,
)

Type Parameters

Type
  • The type of the success value

Methods

chain<HandlerType>(handler: (value: Type) => Result<HandlerType>): Result<HandlerType>

Transforms the Ok value using a function that returns a Result (also known as flatMap).

Similar to map, but the handler function returns a Result instead of a plain value. This is useful for chaining operations that may themselves fail, avoiding nested Results.

getOrElse(defaultValue: Type): Type

Gets the Ok value or returns a default value if this is an Error.

This provides a simple way to extract a value from a Result with a fallback, without needing to use pattern matching.

Checks if this Result represents an error.

Checks if this Result represents a successful value.

map<HandlerType>(handler: (value: Type) => HandlerType): Result<HandlerType>

Transforms the Ok value using the provided function.

If the Result is Ok, applies the handler to the value and returns a new Ok Result. If the Result is Error, returns the Error unchanged without calling the handler.

This allows you to chain transformations on successful values while automatically propagating errors.

mapError(error: ResultError): Result<Type>

Replaces the error with a new error message if this Result is an Error.

This is useful for providing more context to errors, normalizing error messages, or hiding implementation details from callers.

matchWith<
OkReturnType,
ErrorReturnType,
>
(pattern: { Ok: (value: Type) => OkReturnType; Error: (error: ResultError) => ErrorReturnType; }): OkReturnType | ErrorReturnType

Pattern matches on the Result, executing different handlers for Ok and Error cases.

This is the primary way to extract values from a Result. Both cases must be handled, ensuring exhaustive error handling at compile time.

merge(): Type | ResultError

Extracts the value or error from the Result.

This collapses the Result into a single type that could be either the success value or the error. Use this when you need to handle both cases the same way, or when the value and error types are compatible.

orElse<HandlerType>(handler: (value: Result<Type>) => Result<HandlerType>): Result<Type> | Result<HandlerType>

Returns this Result if it's Ok, otherwise calls the handler with the Error.

This allows you to provide an alternative Result when an error occurs, potentially recovering from specific errors or trying alternative approaches.

Static Methods

Error<Type>(error: ResultError): Result<Type>

Creates a failed Result containing an error.

Wraps a Promise into a Result, converting rejections to Error results.

This allows you to work with async operations using the Result pattern, avoiding the need for try/catch blocks.

HasInstance<Type>(value: unknown): value is Result<Type>

Type guard to check if a value is a Result instance.

Ok<Type = void>(value?: Type): Result<Type>

Creates a successful Result containing a value.

Try<Type>(method: () => Type): Result<Type>

Wraps a function that may throw into a Result.

Any exceptions thrown by the function are caught and converted to Error results. This is useful for safely calling code that uses exceptions for error handling.

New Ticket: Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";
or

Import directly with a jsr specifier

import { Result } from "jsr:@folklore/folklore";

Add Package

pnpm i jsr:@folklore/folklore
or (using pnpm 10.8 or older)
pnpm dlx jsr add @folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";

Add Package

yarn add jsr:@folklore/folklore
or (using Yarn 4.8 or older)
yarn dlx jsr add @folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";

Add Package

vlt install jsr:@folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";

Add Package

npx jsr add @folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";

Add Package

bunx jsr add @folklore/folklore

Import symbol

import { Result } from "@folklore/folklore";