@metreeca/core - v0.9.17
    Preparing search index...

    Module relay

    Type-safe relay for discriminated unions.

    Use when working with data where exactly one option is active at a time - like operation results that are either successful or failed, UI states that are loading, ready, or error, or any domain model where alternatives are mutually exclusive.

    The createRelay function lets you handle each option with a dedicated handler, while TypeScript ensures all options are covered and values are accessed safely. Eliminates verbose conditional logic and prevents bugs from unhandled options.

    Basic Pattern Matching

    Define options and match with function handlers:

    import { createRelay } from '@metreeca/core/relay';

    type FieldState = {
    unset: void;
    value: string;
    error: Error;
    };

    const r = createRelay<FieldState>({
    value: "user@example.com"
    });

    const message = r({
    unset: () => "Enter email",
    value: (email) => `Email: ${email}`,
    error: (err) => `Error: ${err.message}`
    });

    Constant Handlers

    Use constant values instead of functions when handlers don't need option data:

    const isValid = r({
    unset: false,
    value: true,
    error: false
    });

    Partial Matching without Fallback

    Handle specific options only, returning undefined for unhandled options:

    const email = r({
    value: (email) => email
    }); // Returns string | undefined

    Partial Matching with Fallback

    Handle specific options and provide a fallback for others:

    const display = r({
    value: (email) => email
    }, "‹blank›");

    Delegation to Fallback

    When a fallback is provided, handlers receive a delegate function to invoke common logic:

    const format = (v: string | Error | void) =>
    v instanceof Error ? `error: ${v.message}` : `value: ${v}`;

    const display = r({
    unset: "Enter email",
    value: (email, delegate) => email.length > 0 ? email : delegate(),
    error: (_err, delegate) => delegate()
    }, format);

    Type Aliases

    Options

    Relay options.

    Option

    Relay option.

    Handlers

    Option handlers.

    Handler

    Option handler.

    Interfaces

    Relay

    Relay.

    Functions

    createRelay

    Creates a type-safe relay function for an option.