or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

algebraic.mdarray.mdeither.mdfunction.mdindex.mdio.mdoption.mdpipeable.mdrecord.mdtask-either.mdtask.mdtype-classes.md
tile.json

either.mddocs/

Either Operations

The Either type represents a value of one of two possible types (a disjoint union). Conventionally, Left represents failure/error and Right represents success/value. Either is right-biased, meaning operations like map and chain operate on Right values.

Capabilities

Core Construction

Create Either instances for success and failure cases.

/**
 * Create a Left instance (typically for errors)
 * @param l - The left/error value
 * @returns Either with left value
 */
function left<L, A>(l: L): Either<L, A>;

/**
 * Create a Right instance (typically for success)
 * @param a - The right/success value
 * @returns Either with right value
 */
function right<L, A>(a: A): Either<L, A>;

/**
 * Convert Option to Either with default left value
 * @param onNone - Value to use for None case
 * @returns Function that converts Option to Either
 */
function fromOption<L>(onNone: L): <A>(fa: Option<A>) => Either<L, A>;

/**
 * Convert nullable to Either with default left value
 * @param defaultValue - Value to use for null/undefined
 * @returns Function that converts nullable to Either
 */
function fromNullable<L>(defaultValue: L): <A>(a: A | null | undefined) => Either<L, A>;

Usage Examples:

import { left, right, fromOption, fromNullable } from "fp-ts/lib/Either";
import { some, none } from "fp-ts/lib/Option";

// Direct construction
const success = right<string, number>(42);
const failure = left<string, number>("Error occurred");

// From Option
const fromOpt = fromOption("No value");
const converted1 = fromOpt(some(100)); // Right(100)
const converted2 = fromOpt(none);      // Left("No value")

// From nullable
const fromNull = fromNullable("Value is null");
const converted3 = fromNull("hello"); // Right("hello")
const converted4 = fromNull(null);    // Left("Value is null")

Safe Execution

Execute functions safely with error handling.

/**
 * Safely execute function that may throw
 * @param f - Function that may throw
 * @param onerror - Error handler (optional, defaults to Error constructor)
 * @returns Either with result or error
 */
function tryCatch<A>(f: Lazy<A>, onerror?: (e: unknown) => Error): Either<Error, A>;

/**
 * Safely execute function with custom error type
 * @param f - Function that may throw
 * @param onerror - Function to convert thrown value to error type
 * @returns Either with result or custom error
 */
function tryCatch2v<L, A>(f: Lazy<A>, onerror: (e: unknown) => L): Either<L, A>;

/**
 * Convert unknown error to Error instance
 * @param e - Unknown error value
 * @returns Error instance
 */
function toError(e: unknown): Error;

Usage Examples:

import { tryCatch, tryCatch2v } from "fp-ts/lib/Either";

// Safe JSON parsing
const parseJSON = (str: string) => tryCatch(
  () => JSON.parse(str),
  (e) => new Error(`Parse error: ${e}`)
);

const result1 = parseJSON('{"name": "Alice"}'); // Right({name: "Alice"})
const result2 = parseJSON('invalid json');     // Left(Error("Parse error: ..."))

// Custom error type
const parseNumber = (str: string) => tryCatch2v(
  () => {
    const num = parseInt(str, 10);
    if (isNaN(num)) throw new Error("Not a number");
    return num;
  },
  (e) => `Parse error: ${e}`
);

Type Guards

Check Either variant and extract information.

/**
 * Type guard to check if Either is Left
 * @param fa - Either to check
 * @returns true if Either is Left
 */
function isLeft<L, A>(fa: Either<L, A>): fa is Left<L, A>;

/**
 * Type guard to check if Either is Right
 * @param fa - Either to check
 * @returns true if Either is Right
 */
function isRight<L, A>(fa: Either<L, A>): fa is Right<L, A>;

Pattern Matching and Extraction

Pattern match on Either variants and extract values.

/**
 * Pattern match on Either with handlers for both cases
 * @param onLeft - Function to call if Either is Left
 * @param onRight - Function to call if Either is Right
 * @returns Function that takes Either and returns result
 */
function fold<E, A, R>(onLeft: (e: E) => R, onRight: (a: A) => R): (ma: Either<E, A>) => R;

/**
 * Extract right value with error handler
 * @param f - Function to convert left value to right type
 * @returns Function that extracts right value or converts left
 */
function getOrElse<E, A>(f: (e: E) => A): (ma: Either<E, A>) => A;

/**
 * Chain alternative Either on Left
 * @param f - Function to convert left value to new Either
 * @returns Function that handles left values
 */
function orElse<E, A, M>(f: (e: E) => Either<M, A>): (ma: Either<E, A>) => Either<M, A>;

Usage Examples:

import { right, left, fold, getOrElse, orElse } from "fp-ts/lib/Either";

const success = right<string, number>(42);
const failure = left<string, number>("Error");

// Pattern matching
const result1 = fold(
  (error: string) => `Failed: ${error}`,
  (value: number) => `Success: ${value}`
)(success); // "Success: 42"

// Extract with default
const result2 = getOrElse((error: string) => 0)(failure); // 0

// Chain alternatives
const withFallback = orElse((error: string) => 
  error === "Error" ? right(0) : left("Fatal error")
);
const result3 = withFallback(failure); // Right(0)

Conditional Operations

Operations based on predicates and conditions.

/**
 * Check if Either contains specific right value
 * @param E - Equality instance for right type
 * @returns Function that checks if Either contains value
 */
function elem<A>(E: Eq<A>): (a: A) => <E>(ma: Either<E, A>) => boolean;

/**
 * Create Either from refinement predicate
 * @param refinement - Type refinement predicate
 * @param onFalse - Function providing left value for false case
 * @returns Function that creates Either based on refinement
 */
function fromRefinement<L, A, B extends A>(
  refinement: Refinement<A, B>, 
  onFalse: (a: A) => L
): (a: A) => Either<L, B>;

JSON Operations

Safe JSON parsing and stringification.

/**
 * Safe JSON parsing
 * @param s - JSON string to parse
 * @param onError - Function to convert parse error to left type
 * @returns Either with parsed result or error
 */
function parseJSON<L>(s: string, onError: (reason: unknown) => L): Either<L, unknown>;

/**
 * Safe JSON stringification
 * @param u - Value to stringify
 * @param onError - Function to convert stringify error to left type
 * @returns Either with JSON string or error
 */
function stringifyJSON<L>(u: unknown, onError: (reason: unknown) => L): Either<L, string>;

Conversions

Convert between Either and other types.

/**
 * Convert Validation to Either
 * @param fa - Validation to convert
 * @returns Either with same left/right types
 */
function fromValidation<L, A>(fa: Validation<L, A>): Either<L, A>;

Type Class Instances

Either implements various type class instances.

/**
 * Main Either type class instances
 */
const either: Monad2<URI> & 
              Foldable2v2<URI> & 
              Traversable2v2<URI> & 
              Bifunctor2<URI> & 
              Alt2<URI> & 
              Extend2<URI> & 
              ChainRec2<URI> & 
              MonadThrow2<URI>;

/**
 * Show instance for Either
 * @param SL - Show instance for left type
 * @param SA - Show instance for right type
 * @returns Show instance for Either
 */
function getShow<L, A>(SL: Show<L>, SA: Show<A>): Show<Either<L, A>>;

/**
 * Equality instance for Either
 * @param EL - Equality instance for left type
 * @param EA - Equality instance for right type
 * @returns Equality instance for Either
 */
function getEq<L, A>(EL: Eq<L>, EA: Eq<A>): Eq<Either<L, A>>;

Semigroup and Monoid Instances

Combine Either values using various strategies.

/**
 * Semigroup for Either (combines Right values)
 * @param S - Semigroup for right type
 * @returns Semigroup for Either
 */
function getSemigroup<L, A>(S: Semigroup<A>): Semigroup<Either<L, A>>;

/**
 * Apply semigroup - combines Right values, returns first Left
 * @param S - Semigroup for right type
 * @returns Semigroup for Either
 */
function getApplySemigroup<L, A>(S: Semigroup<A>): Semigroup<Either<L, A>>;

/**
 * Apply monoid - extends apply semigroup with Right(empty) as identity
 * @param M - Monoid for right type
 * @returns Monoid for Either
 */
function getApplyMonoid<L, A>(M: Monoid<A>): Monoid<Either<L, A>>;

Validation Instances

Special instances for accumulating validation errors.

/**
 * Validation instance that accumulates Left values
 * @param S - Semigroup for left type (error accumulation)
 * @returns Monad and Alt instances for validation
 */
function getValidation<E>(S: Semigroup<E>): Monad2C<URI, E> & Alt2C<URI, E>;

/**
 * Validation semigroup that accumulates both left and right values
 * @param SE - Semigroup for left type
 * @param SA - Semigroup for right type
 * @returns Semigroup for Either
 */
function getValidationSemigroup<E, A>(SE: Semigroup<E>, SA: Semigroup<A>): Semigroup<Either<E, A>>;

/**
 * Validation monoid extending validation semigroup
 * @param SE - Semigroup for left type
 * @param SA - Monoid for right type
 * @returns Monoid for Either
 */
function getValidationMonoid<E, A>(SE: Semigroup<E>, SA: Monoid<A>): Monoid<Either<E, A>>;

Advanced Instances

Specialized instances for complex scenarios.

/**
 * Compactable instance requiring Monoid for left type
 * @param ML - Monoid for left type
 * @returns Compactable instance for Either
 */
function getCompactable<L>(ML: Monoid<L>): Compactable2C<URI, L>;

/**
 * Filterable instance requiring Monoid for left type
 * @param ML - Monoid for left type
 * @returns Filterable instance for Either
 */
function getFilterable<L>(ML: Monoid<L>): Filterable2C<URI, L>;

/**
 * Witherable instance requiring Monoid for left type
 * @param ML - Monoid for left type
 * @returns Witherable instance for Either
 */
function getWitherable<L>(ML: Monoid<L>): Witherable2C<URI, L>;

Error Handling Utilities

Utilities for safe operations that may throw errors.

/**
 * Try catch with error transformation
 * @param f - Function that may throw
 * @param onerror - Function to transform caught error (defaults to creating Error)
 * @returns Either with result or transformed error
 */
function tryCatch<A>(f: Lazy<A>, onerror?: (e: unknown) => Error): Either<Error, A>;

/**
 * Try catch with custom error type (version 2)
 * @param f - Function that may throw
 * @param onerror - Function to transform caught error to custom type
 * @returns Either with result or custom error type
 */
function tryCatch2v<L, A>(f: Lazy<A>, onerror: (e: unknown) => L): Either<L, A>;

/**
 * Parse JSON string safely
 * @param s - JSON string to parse
 * @param onError - Function to handle parse errors
 * @returns Either with parsed value or error
 */
function parseJSON<L>(s: string, onError: (reason: unknown) => L): Either<L, unknown>;

/**
 * Stringify value to JSON safely
 * @param u - Value to stringify
 * @param onError - Function to handle stringify errors
 * @returns Either with JSON string or error
 */
function stringifyJSON<L>(u: unknown, onError: (reason: unknown) => L): Either<L, string>;

Types

// Core Either type
type Either<L, A> = Left<L, A> | Right<L, A>;

// Either variants
class Left<L, A> {
  readonly _tag: 'Left' = 'Left';
  readonly _A!: A;
  readonly _L!: L;
  readonly _URI!: URI;
  constructor(readonly value: L) {}
}

class Right<L, A> {
  readonly _tag: 'Right' = 'Right';
  readonly _A!: A;
  readonly _L!: L;
  readonly _URI!: URI;
  constructor(readonly value: A) {}
}

// URI for type-level programming
const URI = 'Either';
type URI = typeof URI;