result.ts

view source

Declarations
#

6 declarations

NOT_OK
#

result.ts view source

Readonly<{ readonly ok: false; }> import {NOT_OK} from '@fuzdev/fuz_util/result.js';

Frozen object representing a failed result.

OK
#

result.ts view source

Readonly<{ readonly ok: true; }> import {OK} from '@fuzdev/fuz_util/result.js';

Frozen object representing a successful result.

Result
#

result.ts view source

Result<TValue, TError> import type {Result} from '@fuzdev/fuz_util/result.js';

An alternative pattern to throwing and catching errors. Uses the type system to strongly type error return values when desired. Catching errors is then reserved for unexpected situations.

generics

Result<TValue = object, TError = object>
TValue
default object
TError
default object

ResultError
#

result.ts view source

import {ResultError} from '@fuzdev/fuz_util/result.js';

A custom error class that's thrown by unwrap. Wraps a failed Result with an optional message, and also accepts an optional message that overrides the result's. Useful for generic handling of unwrapped results to forward custom messages and other failed result data.

inheritance

extends: Error

DEFAULT_MESSAGE

type string

static

result

type { ok: false; message?: string }

readonly

constructor

type new (result: { ok: false; message?: string | undefined; }, message?: string | undefined, options?: ErrorOptions | undefined): ResultError

result

type { ok: false; message?: string | undefined; }

message?

type string | undefined
optional

options?

type ErrorOptions | undefined
optional

unwrap
#

result.ts view source

<TValue extends { value?: unknown; }, TError extends { message?: string; }>(result: Result<TValue, TError>, message?: string | undefined): TValue["value"] import {unwrap} from '@fuzdev/fuz_util/result.js';

A helper that says, "hey I know this is wrapped in a Result, but I expect it to be ok, so if it's not, I understand it will throw an error that wraps the result".

result

type Result<TValue, TError>

message?

type string | undefined
optional

returns

TValue["value"]

generics

unwrap<TValue extends { value?: unknown }, TError extends { message?: string }>
TValue
constraint { value?: unknown }
TError
constraint { message?: string }

throws

  • ResultError - if `result.ok` is false

unwrap_error
#

result.ts view source

<TError extends object>(result: Result<object, TError>, message?: string): { ok: false; } & TError import {unwrap_error} from '@fuzdev/fuz_util/result.js';

A helper that does the opposite of unwrap, throwing if the Result is ok. Note that while unwrap returns the wrapped value, unwrap_error returns the entire result.

result

type Result<object, TError>

message

type string
default 'Failed to unwrap result error'

returns

{ ok: false; } & TError

generics

unwrap_error<TError extends object>
TError
constraint object

throws

  • Error - if `result.ok` is true

Imported by
#