result.ts

Declarations
#

6 declarations

view source

NOT_OK
#

result.ts view source

Readonly<{ readonly ok: false; }>

Frozen object representing a failed result.

OK
#

result.ts view source

Readonly<{ readonly ok: true; }>

Frozen object representing a successful result.

Result
#

result.ts view source

Result<TValue, TError>

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

TValue

default object

TError

default object

ResultError
#

result.ts view source

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

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"]

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

Some Result object.

type Result<TValue, TError>

message?

Optional custom error message.

type string | undefined
optional

returns

TValue["value"]

The wrapped value.

unwrap_error
#

result.ts view source

<TError extends object>(result: Result<object, TError>, message?: string): { ok: false; } & TError

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

Some Result object.

type Result<object, TError>

message

Optional custom error message.

type string
default 'Failed to unwrap result error'

returns

{ ok: false; } & TError

The type-narrowed result.