For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt, and this page is available as Markdown at /byethrow/guide/tutorial/basics/parsing-values.md.
  • English
  • Parsing Values

    Data that comes from outside your program, such as request bodies, JSON files, or environment variables, is unknown until it has been validated. parse validates such a value against a schema and returns the outcome as a Result.

    Validating with parse

    parse(schema, value)Select a case to follow its path

    parse accepts any schema that implements Standard Schema, the common interface supported by validation libraries such as Zod, Valibot, and ArkType. The examples on this page use Zod:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    import z
    z
    } from 'zod';
    const
    const User: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    User
    =
    import z
    z
    .
    function object<{
        name: z.ZodString;
        email: z.ZodEmail;
    }>(shape?: {
        name: z.ZodString;
        email: z.ZodEmail;
    } | undefined, params?: string | {
        error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
        message?: string | undefined | undefined;
    } | undefined): z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    object
    ({
    name: z.ZodString
    name
    :
    import z
    z
    .
    function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)
    string
    ().
    _ZodString<$ZodStringInternals<string>>.min(minLength: number, params?: string | z.core.$ZodCheckMinLengthParams): z.ZodString
    min
    (1),
    email: z.ZodEmail
    email
    :
    import z
    z
    .
    function email(params?: string | z.core.$ZodEmailParams): z.ZodEmail
    email
    (),
    }); const
    const result: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>
    result
    =
    import Result
    Result
    .
    function parse<z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>>(schema: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>, value: unknown): Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    const User: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    User
    , {
    name: string
    name
    : 'Alice',
    email: string
    email
    : 'alice@example.com' });
    // Type: Result.Result<{ name: string; email: string }, ReadonlyArray<StandardSchemaV1.Issue>>

    If the value matches the schema, the result is a Success holding the parsed value, typed according to the schema. Otherwise, the result is a Failure holding the list of validation issues.

    Reading Validation Issues

    Each issue has a message and, optionally, a path pointing to the invalid property:

    const 
    const result: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>
    result
    =
    import Result
    Result
    .
    function parse<z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>>(schema: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>, value: unknown): Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    const User: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    User
    , {
    name: string
    name
    : '',
    email: string
    email
    : 'not an email' });
    if (
    import Result
    Result
    .
    function isFailure<Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(result: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>): result is Result.Failure<readonly StandardSchemaV1.Issue[]>

    Type guard to check if a Result is a Failure .

    @typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
    if (Result.isFailure(result)) {
      console.error(result.error); // Safe access to error
    }
    @categoryType Guards
    isFailure
    (
    const result: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>
    result
    )) {
    for (const
    const issue: StandardSchemaV1.Issue
    issue
    of
    const result: Result.Failure<readonly StandardSchemaV1.Issue[]>
    result
    .
    error: readonly StandardSchemaV1.Issue[]
    error
    ) {
    var console: Console
    console
    .
    Console.log(...data: any[]): void

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

    MDN Reference

    log
    (
    const issue: StandardSchemaV1.Issue
    issue
    .
    StandardSchemaV1<Input = unknown, Output = Input>.Issue.path?: readonly (PropertyKey | StandardSchemaV1.PathSegment)[] | undefined

    The path of the issue, if any.

    path
    ,
    const issue: StandardSchemaV1.Issue
    issue
    .
    StandardSchemaV1<Input = unknown, Output = Input>.Issue.message: string

    The error message of the issue.

    message
    );
    } }

    Using parse in a Pipeline

    When called with only a schema, parse returns a function that validates its argument. This form fits naturally into a pipeline, which you will learn about in Pipe Basics:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const parseJson: (text: string) => Result.Result<unknown, Error>
    parseJson
    =
    import Result
    Result
    .
    function fn<(text: string) => unknown, Error>(options: {
        try: (text: string) => unknown;
        catch: (error: unknown) => Error;
    }): (text: string) => Result.Result<unknown, Error> (+3 overloads)

    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.

    @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: (text: string) => unknown
    try
    : (
    text: string
    text
    : string) =>
    var JSON: JSON

    An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

    JSON
    .
    JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any

    Converts a JavaScript Object Notation (JSON) string into an object.

    @paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON.
    parse
    (
    text: string
    text
    ) as unknown,
    catch: (error: unknown) => Error
    catch
    : (
    error: unknown
    error
    ) => new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Invalid JSON', {
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); const
    const parseUser: (text: string) => Result.Result<{
        name: string;
        email: string;
    }, Error | readonly StandardSchemaV1.Issue[]>
    parseUser
    = (
    text: string
    text
    : string) =>
    import Result
    Result
    .
    function pipe<Result.Result<unknown, Error>, Result.Result<{
        name: string;
        email: string;
    }, Error | readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(a: Result.Result<unknown, Error>, ab: (a: Result.Result<unknown, Error>) => Result.Result<{
        name: string;
        email: string;
    }, Error | readonly StandardSchemaV1.Issue[]>): Result.Result<{
        name: string;
        email: string;
    }, Error | readonly StandardSchemaV1.Issue[]> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const parseJson: (text: string) => Result.Result<unknown, Error>
    parseJson
    (
    text: string
    text
    ),
    import Result
    Result
    .
    function andThen<Result.Result<unknown, Error>, Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(fn: (a: unknown) => Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>): (result: Result.Result<unknown, Error>) => Result.Result<{
        name: string;
        email: string;
    }, Error | readonly StandardSchemaV1.Issue[]> (+1 overload)

    Chains 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.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    (
    import Result
    Result
    .
    function parse<z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>>(schema: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>): (value: unknown) => Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    const User: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    User
    )),
    );

    To replace the list of issues with your own error type, use mapError:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    class
    class ValidationError
    ValidationError
    extends
    var Error: ErrorConstructor
    Error
    {
    override readonly
    ValidationError.name: "ValidationError"
    name
    = 'ValidationError';
    } const
    const validateUser: (input: unknown) => Result.Result<{
        name: string;
        email: string;
    }, ValidationError>
    validateUser
    = (
    input: unknown
    input
    : unknown) =>
    import Result
    Result
    .
    function pipe<unknown, Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<{
        name: string;
        email: string;
    }, ValidationError>>(a: unknown, ab: (a: unknown) => Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>) => Result.Result<{
        name: string;
        email: string;
    }, ValidationError>): Result.Result<{
        name: string;
        email: string;
    }, ValidationError> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    input: unknown
    input
    ,
    import Result
    Result
    .
    function parse<z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>>(schema: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>): (value: unknown) => Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)

    Parses a value using a https://github.com/standard-schema/standard-schema Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.

    @typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@example

    Basic Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const result = Result.parse(schema, { name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @example

    Curried Usage

    import { Result } from '@praha/byethrow';
    import { z } from 'zod';
    
    const schema = z.object({ name: z.string() });
    const parser = Result.parse(schema);
    const result = parser({ name: 'John' });
    // Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
    @categoryUtilities
    parse
    (
    const User: z.ZodObject<{
        name: z.ZodString;
        email: z.ZodEmail;
    }, z.core.$strip>
    User
    ),
    import Result
    Result
    .
    function mapError<Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, ValidationError>(fn: (a: readonly StandardSchemaV1.Issue[]) => ValidationError): (result: Result.Result<{
        name: string;
        email: string;
    }, readonly StandardSchemaV1.Issue[]>) => Result.Result<{
        name: string;
        email: string;
    }, ValidationError> (+1 overload)

    Applies a transformation function to the error value of a Result or ResultAsync . If the input is a Success , it will be returned unchanged.

    @typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@example

    Failure Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('NotFound'),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Failure', error: Error('NotFound') }
    @example

    Success Case (unchanged)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(123),
    Result.mapError((error) => new Error(error)),
    );
    // { type: 'Success', value: 123 }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    mapError
    ((
    issues: readonly StandardSchemaV1.Issue[]
    issues
    ) => new
    constructor ValidationError(message?: string, options?: ErrorOptions): ValidationError (+1 overload)
    ValidationError
    ('Invalid user', {
    ErrorOptions.cause?: unknown
    cause
    :
    issues: readonly StandardSchemaV1.Issue[]
    issues
    })),
    );
    Warning

    parse only supports synchronous validation. If the schema performs asynchronous validation (for example, an async refinement), parse throws a TypeError.

    References

    APIPurpose
    parse(schema, value)Validate a value with a Standard Schema