• 日本語
  • Namespace: Result

    Re-exports core Result-handling utilities under two convenient namespaces:

    • Result: Verbose and explicit usage
    • R: Shorthand alias for more concise code

    Examples

    Basic Usage

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const validateId: (id: string) => Result.Failure<Error> | Result.Success<void>
    validateId
    = (
    id: string
    id
    : string) => {
    if (!
    id: string
    id
    .
    String.startsWith(searchString: string, position?: number): boolean

    Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

    startsWith
    ('u')) {
    return
    import Result
    Result
    .
    const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
    fail
    (new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Invalid ID format'));
    } return
    import Result
    Result
    .
    const succeed: () => Result.ResultFor<never, void, never> (+1 overload)
    succeed
    ();
    }; const
    const findUser: (id: string) => Result.Result<{
        id: string;
        name: string;
    }, Error>
    findUser
    =
    import Result
    Result
    .
    fn<(id: string) => {
        id: string;
        name: string;
    }, Error>(options: {
        try: (id: string) => {
            id: string;
            name: string;
        };
        catch: (error: unknown) => Error;
    }): (id: string) => Result.Result<{
        id: string;
        name: string;
    }, Error> (+3 overloads)
    export fn

    Wraps a function that may throw and returns a new function that returns a Result or ResultAsync .

    You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

    @function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: (x: number) => {
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = fn(5); // Result.Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: (x: number) => x + 1,
    });
    
    const result = fn(1); // Result.Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });
    
    const result = await fn(); // Result.ResultAsync<string, never>
    @categoryCreators
    fn
    ({
    try: (id: string) => {
        id: string;
        name: string;
    }
    try
    : (
    id: string
    id
    : string) => {
    return {
    id: string
    id
    ,
    name: string
    name
    : 'John Doe' };
    },
    catch: (error: unknown) => Error
    catch
    : (
    error: unknown
    error
    ) => new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Failed to find user', {
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); const
    const result: Result.Result<{
        id: string;
        name: string;
    }, Error>
    result
    =
    import Result
    Result
    .
    const pipe: <Result.Result<"u123", never>, Result.Result<"u123", Error>, Result.Result<{
        id: string;
        name: string;
    }, Error>>(a: Result.Result<"u123", never>, ab: (a: Result.Result<"u123", never>) => Result.Result<"u123", Error>, bc: (b: Result.Result<"u123", Error>) => Result.Result<{
        id: string;
        name: string;
    }, Error>) => Result.Result<{
        id: string;
        name: string;
    }, Error> (+25 overloads)
    pipe
    (
    import Result
    Result
    .
    const succeed: <"u123">(value: "u123") => Result.Result<"u123", never> (+1 overload)
    succeed
    ('u123'),
    import Result
    Result
    .
    const andThrough: <Result.Result<"u123", never>, Result.Failure<Error> | Result.Success<void>>(fn: (a: "u123") => Result.Failure<Error> | Result.Success<void>) => (result: Result.Result<"u123", never>) => Result.Result<"u123", Error> (+1 overload)
    andThrough
    (
    const validateId: (id: string) => Result.Failure<Error> | Result.Success<void>
    validateId
    ),
    import Result
    Result
    .
    const andThen: <Result.Result<"u123", Error>, Result.Result<{
        id: string;
        name: string;
    }, Error>>(fn: (a: "u123") => Result.Result<{
        id: string;
        name: string;
    }, Error>) => (result: Result.Result<"u123", Error>) => Result.Result<{
        id: string;
        name: string;
    }, Error> (+1 overload)
    andThen
    (
    const findUser: (id: string) => Result.Result<{
        id: string;
        name: string;
    }, Error>
    findUser
    ),
    ); if (
    import Result
    Result
    .
    const isSuccess: <Result.Result<{
        id: string;
        name: string;
    }, Error>>(result: Result.Result<{
        id: string;
        name: string;
    }, Error>) => result is Result.Success<{
        id: string;
        name: string;
    }>

    Type guard to check if a Result is a Success .

    @function@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Success', value: 10 };
    if (Result.isSuccess(result)) {
      console.log(result.value); // Safe access to value
    }
    @categoryType Guards
    isSuccess
    (
    const result: Result.Result<{
        id: string;
        name: string;
    }, Error>
    result
    )) {
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    (
    const result: Result.Success<{
        id: string;
        name: string;
    }>
    result
    .
    value: {
        id: string;
        name: string;
    }
    value
    ); // User found: John Doe
    }

    Shorthand Usage

    import { 
    import R
    R
    } from '@praha/byethrow';
    const
    const validateId: (id: string) => R.Failure<Error> | R.Success<void>
    validateId
    = (
    id: string
    id
    : string) => {
    if (!
    id: string
    id
    .
    String.startsWith(searchString: string, position?: number): boolean

    Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

    startsWith
    ('u')) {
    return
    import R
    R
    .
    const fail: <Error>(error: Error) => R.Result<never, Error> (+1 overload)
    fail
    (new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Invalid ID format'));
    } return
    import R
    R
    .
    const succeed: () => R.ResultFor<never, void, never> (+1 overload)
    succeed
    ();
    }; const
    const findUser: (id: string) => R.Result<{
        id: string;
        name: string;
    }, Error>
    findUser
    =
    import R
    R
    .
    fn<(id: string) => {
        id: string;
        name: string;
    }, Error>(options: {
        try: (id: string) => {
            id: string;
            name: string;
        };
        catch: (error: unknown) => Error;
    }): (id: string) => R.Result<{
        id: string;
        name: string;
    }, Error> (+3 overloads)
    export fn

    Wraps a function that may throw and returns a new function that returns a Result or ResultAsync .

    You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

    @function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: (x: number) => {
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = fn(5); // Result.Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: (x: number) => x + 1,
    });
    
    const result = fn(1); // Result.Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });
    
    const result = await fn(); // Result.ResultAsync<string, never>
    @categoryCreators
    fn
    ({
    try: (id: string) => {
        id: string;
        name: string;
    }
    try
    : (
    id: string
    id
    : string) => {
    return {
    id: string
    id
    ,
    name: string
    name
    : 'John Doe' };
    },
    catch: (error: unknown) => Error
    catch
    : (
    error: unknown
    error
    ) => new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Failed to find user', {
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); const
    const result: R.Result<{
        id: string;
        name: string;
    }, Error>
    result
    =
    import R
    R
    .
    const pipe: <R.Result<"u123", never>, R.Result<"u123", Error>, R.Result<{
        id: string;
        name: string;
    }, Error>>(a: R.Result<"u123", never>, ab: (a: R.Result<"u123", never>) => R.Result<"u123", Error>, bc: (b: R.Result<"u123", Error>) => R.Result<{
        id: string;
        name: string;
    }, Error>) => R.Result<{
        id: string;
        name: string;
    }, Error> (+25 overloads)
    pipe
    (
    import R
    R
    .
    const succeed: <"u123">(value: "u123") => R.Result<"u123", never> (+1 overload)
    succeed
    ('u123'),
    import R
    R
    .
    const andThrough: <R.Result<"u123", never>, R.Failure<Error> | R.Success<void>>(fn: (a: "u123") => R.Failure<Error> | R.Success<void>) => (result: R.Result<"u123", never>) => R.Result<"u123", Error> (+1 overload)
    andThrough
    (
    const validateId: (id: string) => R.Failure<Error> | R.Success<void>
    validateId
    ),
    import R
    R
    .
    const andThen: <R.Result<"u123", Error>, R.Result<{
        id: string;
        name: string;
    }, Error>>(fn: (a: "u123") => R.Result<{
        id: string;
        name: string;
    }, Error>) => (result: R.Result<"u123", Error>) => R.Result<{
        id: string;
        name: string;
    }, Error> (+1 overload)
    andThen
    (
    const findUser: (id: string) => R.Result<{
        id: string;
        name: string;
    }, Error>
    findUser
    ),
    ); if (
    import R
    R
    .
    const isSuccess: <R.Result<{
        id: string;
        name: string;
    }, Error>>(result: R.Result<{
        id: string;
        name: string;
    }, Error>) => result is R.Success<{
        id: string;
        name: string;
    }>

    Type guard to check if a Result is a Success .

    @function@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Success', value: 10 };
    if (Result.isSuccess(result)) {
      console.log(result.value); // Safe access to value
    }
    @categoryType Guards
    isSuccess
    (
    const result: R.Result<{
        id: string;
        name: string;
    }, Error>
    result
    )) {
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    (
    const result: R.Success<{
        id: string;
        name: string;
    }>
    result
    .
    value: {
        id: string;
        name: string;
    }
    value
    ); // User found: John Doe
    }

    Core Types

    Type AliasDescription
    FailureRepresents a failed result.
    ResultA union type representing either a success or a failure.
    ResultAsyncAn asynchronous variant of Result, wrapped in a Promise.
    ResultForResolves to the appropriate Result type (sync or async) based on the input type.
    ResultMaybeAsyncA result that may be either synchronous or asynchronous.
    SuccessRepresents a successful result.

    Infer Types

    Type AliasDescription
    InferFailureInfers the Failure value type E from a Result or a function returning a Result.
    InferSuccessInfers the Success value type T from a Result or a function returning a Result.

    Creators

    FunctionDescription
    doAlias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
    failCreates a Failure result from a given error. Automatically wraps the error in a Promise if it is asynchronous.
    fnWraps a function that may throw and returns a new function that returns a Result or ResultAsync.
    succeedCreates a Success result from a given value. Automatically wraps the value in a Promise if it is asynchronous.
    tryExecutes a function that may throw and wraps the result in a Result or ResultAsync.

    Combinators

    FunctionDescription
    andThenChains the next computation using the success value of a Result or ResultAsync. If the original result is a Failure, it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.
    andThroughRuns an additional computation using the success value of a Result or ResultAsync, but returns the original result if the additional computation is successful.
    bindChains another Result-producing computation and merges its success value into the existing object under the specified key.
    inspectExecutes a side effect function on the success value of a Result or ResultAsync, without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state.
    inspectErrorExecutes a side effect function on the error value of a Result or ResultAsync, without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state.
    mapApplies a transformation function to the success value of a Result or ResultAsync. If the input is a Failure, it will be returned unchanged.
    mapErrorApplies a transformation function to the error value of a Result or ResultAsync. If the input is a Success, it will be returned unchanged.
    orElseChains the next computation using the error value of a Result or ResultAsync. If the original result is a Success, it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.
    orThroughRuns an additional computation using the error value of a Result or ResultAsync, but returns the original failure if the additional computation is successful.

    Unwraps

    FunctionDescription
    unwrapExtracts the success value from a Result or ResultAsync.
    unwrapErrorExtracts the error value from a Result or ResultAsync.

    Assertions

    FunctionDescription
    assertFailureAsserts that a Result or ResultAsync is a Failure and returns it. This function requires that the result's success type is never, meaning the result is guaranteed to be a Failure at the type level. If the result is a Success at runtime, throws an error.
    assertSuccessAsserts that a Result or ResultAsync is a Success and returns it. This function requires that the result's error type is never, meaning the result is guaranteed to be a Success at the type level. If the result is a Failure at runtime, throws an error.

    Type Guards

    FunctionDescription
    isFailureType guard to check if a Result is a Failure.
    isResultType guard to check if a value is a Result.
    isSuccessType guard to check if a Result is a Success.

    Utilities

    FunctionDescription
    collectProcesses multiple Result or ResultAsync values into a single result. If all results are Success, returns a Success containing all values. If any result is a Failure, returns a Failure containing an array of all errors.
    parseParses a value using a Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.
    pipeApplies a sequence of functions to a value, from left to right.
    sequenceProcesses multiple Result or ResultAsync values into a single result. If all results are Success, returns a Success containing all values. If any result is a Failure, immediately stops processing and returns a Failure with that single error.