Skip to content

Class: Ok<T, E>

Defined in: core/ok.ts:26

Internal

Represents a successful Result containing a value.

Ok is a Result variant that encapsulates successful operations. Provides methods to transform, chain, and extract the contained value, as well as convert to other representations.

Remarks

You normally don't instantiate Ok directly. Use Result.ok(value).

Example

ts
const result = Result.ok(42)
console.log(result.unwrap()) // 42
console.log(result.isOk())   // true

Type Parameters

T

T

Success value type

E

E = never

Error type (for type compatibility)

Implements

  • ResultMethods<T, E>

Constructors

Constructor

new Ok<T, E>(value): Ok<T, E>

Defined in: core/ok.ts:29

Parameters

value

T

Returns

Ok<T, E>

Accessing

err

Get Signature

get err(): null

Defined in: core/ok.ts:139

Gets the error or null.

Example
ts
Result.ok(42).err // null
Returns

null

Always null for Ok

Implementation of

ResultMethods.err


ok

Get Signature

get ok(): T

Defined in: core/ok.ts:126

Gets the success value or null.

Read-only property for safe value access without throwing exceptions.

Examples
ts
const result = Result.ok(42)
console.log(result.ok) // 42
ts
const err = Result.err('fail')
console.log(err.ok) // null
Returns

T

The encapsulated value

Implementation of

ResultMethods.ok


expect()

expect(_message): T

Defined in: core/ok.ts:236

Extracts value with custom error message (for Err).

For Ok, ignores the message and returns the value. For Err, would throw error with the provided message.

Parameters

_message

string

Error message (ignored for Ok)

Returns

T

The encapsulated value

See

expectErr for Err variant

Example

ts
const value = Result.ok(42).expect('should exist')
console.log(value) // 42

Implementation of

ResultMethods.expect


expectErr()

expectErr(message): never

Defined in: core/ok.ts:252

Attempts to extract error with custom message (always fails for Ok).

Parameters

message

string

Error message

Returns

never

Never returns

Throws

Always throws with provided message

Example

ts
Result.ok(42).expectErr('should be error')
// throws Error("should be error: 42")

Implementation of

ResultMethods.expectErr


unwrap()

unwrap(): T

Defined in: core/ok.ts:164

Extracts the success value.

For Ok, returns the encapsulated value. Equivalent to accessing .ok. Use when you're sure the Result is Ok.

Returns

T

The encapsulated value

See

Examples

ts
const value = Result.ok(42).unwrap()
console.log(value) // 42
ts
// Usage after checking
if (result.isOk()) {
  const value = result.unwrap() // safe
}

Implementation of

ResultMethods.unwrap


unwrapErr()

unwrapErr(): never

Defined in: core/ok.ts:179

Attempts to extract the error (always fails for Ok).

Returns

never

Never returns

Throws

Always throws error indicating incorrect usage

Example

ts
Result.ok(42).unwrapErr()
// throws Error("Called unwrapErr on an Ok value: 42")

Implementation of

ResultMethods.unwrapErr


unwrapOr()

unwrapOr(_defaultValue): T

Defined in: core/ok.ts:199

Extracts value or returns default.

For Ok, ignores the default and returns the value. For Err, would return the default.

Parameters

_defaultValue

T

Default value (ignored for Ok)

Returns

T

The encapsulated value

See

Example

ts
Result.ok(42).unwrapOr(0) // 42
Result.err('fail').unwrapOr(0) // 0

Implementation of

ResultMethods.unwrapOr


unwrapOrElse()

unwrapOrElse(_onError): T

Defined in: core/ok.ts:217

Extracts value or computes default from error.

For Ok, ignores the function and returns the value.

Parameters

_onError

(error) => T

Default value generator (ignored)

Returns

T

The encapsulated value

See

unwrapOr for static default

Example

ts
Result.ok(42).unwrapOrElse((e) => 0) // 42
Result.err('fail').unwrapOrElse((e) => 0) // 0

Implementation of

ResultMethods.unwrapOrElse

Async

andAsync()

andAsync<U>(result): AsyncResult<U, E>

Defined in: core/ok.ts:881

Returns async Result if this is Ok.

Type Parameters

U

U

Second Result success type

Parameters

result

AsyncResult<U, E>

Async Result

Returns

AsyncResult<U, E>

The provided Promise

Example

ts
await Result.ok(5).andAsync(
  Promise.resolve(Result.ok(10))
)
// Ok(10)

Implementation of

ResultMethods.andAsync


andThenAsync()

andThenAsync<U>(mapAsync): AsyncResult<U, E>

Defined in: core/ok.ts:863

Chains async operation that returns Result.

Type Parameters

U

U

New success type

Parameters

mapAsync

(value) => AsyncResult<U, E>

Async chaining

Returns

AsyncResult<U, E>

Promise of returned Result

Example

ts
await Result.ok(userId).andThenAsync(async (id) => {
  const user = await fetchUser(id)
  return user ? Result.ok(user) : Result.err('not found')
})

Implementation of

ResultMethods.andThenAsync


mapAsync()

mapAsync<U>(mapperAsync): AsyncResult<U, E>

Defined in: core/ok.ts:789

Transforms value asynchronously.

Async version of map().

Type Parameters

U

U

Transformed value type

Parameters

mapperAsync

(value) => Promise<U>

Async transformation function

Returns

AsyncResult<U, E>

Promise of transformed Ok

Examples

ts
await Result.ok(5).mapAsync(async (x) => x * 2)
// Ok(10)
ts
await Result.ok(userId).mapAsync(async (id) => {
  return await fetchUser(id)
})
// Ok(user)

Implementation of

ResultMethods.mapAsync


mapErrAsync()

mapErrAsync<E2>(_mapperAsync): AsyncResult<T, E2>

Defined in: core/ok.ts:805

Transforms error asynchronously (not applicable for Ok).

Type Parameters

E2

E2

New error type

Parameters

_mapperAsync

(error) => Promise<E2>

Async transformation (ignored)

Returns

AsyncResult<T, E2>

Promise of Ok with same value

Example

ts
await Result.ok(5).mapErrAsync(async (e) => e + 1)
// Ok(5)

Implementation of

ResultMethods.mapErrAsync


mapOrAsync()

mapOrAsync<U>(mapperAsync, _defaultValue): Promise<U>

Defined in: core/ok.ts:822

Transforms value asynchronously or returns default.

Type Parameters

U

U

Transformed value type

Parameters

mapperAsync

(value) => Promise<U>

Async transformation

_defaultValue

U

Default value (ignored)

Returns

Promise<U>

Promise of transformed value

Example

ts
await Result.ok(5).mapOrAsync(async (x) => x * 2, 0)
// 10

Implementation of

ResultMethods.mapOrAsync


mapOrElseAsync()

mapOrElseAsync<U>(okAsync, _errAsync): Promise<U>

Defined in: core/ok.ts:842

Transforms using appropriate async mapper.

Type Parameters

U

U

Result type

Parameters

okAsync

(value) => Promise<U>

Async success mapper

_errAsync

(error) => Promise<U>

Error mapper (ignored)

Returns

Promise<U>

Promise of transformed value

Example

ts
await Result.ok(5).mapOrElseAsync(
  async (x) => x * 2,
  async (e) => -1
)
// 10

Implementation of

ResultMethods.mapOrElseAsync


orAsync()

orAsync(_result): AsyncResult<T, E>

Defined in: core/ok.ts:898

Returns this Result or async alternative.

Parameters

_result

AsyncResult<T, E>

Async alternative (ignored)

Returns

AsyncResult<T, E>

Promise of this instance

Example

ts
await Result.ok(5).orAsync(
  Promise.resolve(Result.ok(10))
)
// Ok(5)

Implementation of

ResultMethods.orAsync


orElseAsync()

orElseAsync(_onErrorAsync): AsyncResult<T, E>

Defined in: core/ok.ts:915

Returns this Result or executes async recovery.

Parameters

_onErrorAsync

(error) => AsyncResult<T, E>

Async recovery (ignored)

Returns

AsyncResult<T, E>

Promise of this instance

Example

ts
await Result.ok(5).orElseAsync(
  async (e) => Result.ok(0)
)
// Ok(5)

Implementation of

ResultMethods.orElseAsync

Chaining

and()

and<U>(result): Result<U, E>

Defined in: core/ok.ts:466

Returns second Result if this is Ok.

For Ok, returns the provided Result. For Err, would keep the error.

Type Parameters

U

U

Second Result success type

Parameters

result

Result<U, E>

Result to return

Returns

Result<U, E>

The provided Result

See

Example

ts
Result.ok(1).and(Result.ok(2))
// Ok(2)

Result.ok(1).and(Result.err('fail'))
// Err("fail")

Implementation of

ResultMethods.and


andThen()

andThen<U>(flatMapper): Result<U, E>

Defined in: core/ok.ts:499

Chains operation that returns Result.

Similar to map(), but mapper must return Result explicitly. Doesn't do automatic flattening.

Type Parameters

U

U

New success type

Parameters

flatMapper

(value) => Result<U, E>

Chaining function

Returns

Result<U, E>

Result returned by flatMapper

See

Examples

ts
Result.ok(5).andThen((x) => Result.ok(x * 2))
// Ok(10)

Result.ok(5).andThen((x) => Result.err('failure'))
// Err("failure")
ts
// Validation pipeline
Result.ok(userData)
  .andThen(validateEmail)
  .andThen(validateAge)
  .andThen(saveToDatabase)

Implementation of

ResultMethods.andThen


or()

or(result): Result<T, E>

Defined in: core/ok.ts:521

Returns this Result or alternative.

For Ok, ignores alternative and returns self.

Parameters

result

Result<T, E>

Alternative Result (ignored)

Returns

Result<T, E>

This Ok instance

See

Example

ts
Result.ok(1).or(Result.ok(2))
// Ok(1)

Result.ok(1).or(Result.err('fail'))
// Ok(1)

Implementation of

ResultMethods.or


orElse()

orElse(_onError): Result<T, E>

Defined in: core/ok.ts:543

Returns this Result or executes error recovery.

For Ok, ignores recovery and returns self. For Err, would execute the recovery function.

Parameters

_onError

(error) => Result<T, E>

Recovery (ignored)

Returns

Result<T, E>

This Ok instance

See

Example

ts
Result.ok(42).orElse((e) => Result.ok(0))
// Ok(42)

Implementation of

ResultMethods.orElse


zip()

zip<U, E2>(result): Result<[T, U], E | E2>

Defined in: core/ok.ts:574

Combines two Results into tuple.

If both are Ok, returns Ok with tuple [this, other]. If other is Err, returns that Err.

Type Parameters

U

U

Second Result success type

E2

E2

Second Result error type

Parameters

result

Result<U, E2>

Result to combine

Returns

Result<[T, U], E | E2>

Ok with tuple or first Err

See

and for chaining and discarding the first Ok value.

Examples

ts
Result.ok(1).zip(Result.ok(2))
// Ok([1, 2])

Result.ok(1).zip(Result.err('fail'))
// Err("fail")
ts
// Combining multiple operations
const userId = getUserId()
const userName = getUserName()
const combined = userId.zip(userName)
// Ok([id, name]) or first error

Implementation of

ResultMethods.zip

Checking

isErr()

isErr(): this is Err<E, Error>

Defined in: core/ok.ts:66

Checks if this Result is the Err variant.

Returns

this is Err<E, Error>

Always false for Ok

See

isOk for the opposite check

Example

ts
Result.ok(42).isErr() // false

Implementation of

ResultMethods.isErr


isErrAnd()

isErrAnd(_predicate): this is Err<E, Error>

Defined in: core/ok.ts:102

Checks if it's Err and if the error satisfies a predicate.

Parameters

_predicate

(error) => boolean

Validation function (ignored)

Returns

this is Err<E, Error>

Always false for Ok

See

isErrAnd for the opposite check

Implementation of

ResultMethods.isErrAnd


isOk()

isOk(): this is Ok<T, never>

Defined in: core/ok.ts:52

Checks if this Result is the Ok variant.

Returns

this is Ok<T, never>

Always true for Ok

See

isErr for the opposite check

Example

ts
Result.ok(42).isOk()       // true
Result.err('fail').isOk()  // false

Implementation of

ResultMethods.isOk


isOkAnd()

isOkAnd(predicate): this is Ok<T, never>

Defined in: core/ok.ts:90

Checks if it's Ok and if the value satisfies a predicate.

Useful for conditional validations in chains.

Parameters

predicate

(value) => boolean

Validation function

Returns

this is Ok<T, never>

true if Ok and predicate passes

See

isOkAnd for the opposite check

Examples

ts
Result.ok(10).isOkAnd((x) => x > 5)  // true
Result.ok(3).isOkAnd((x) => x > 5)   // false
ts
// Conditional validation
if (result.isOkAnd((user) => user.isActive)) {
  // User exists AND is active
}

Implementation of

ResultMethods.isOkAnd

Conversion

toJSON()

toJSON(): object

Defined in: core/ok.ts:761

Converts Result to JSON object.

Useful for serialization and APIs.

Returns

object

JSON representation

type

type: "ok"

value

value: T

Example

ts
Result.ok(42).toJSON()
// { type: 'ok', value: 42 }

JSON.stringify(Result.ok(42))
// '{"type":"ok","value":42}'

Implementation of

ResultMethods.toJSON


toPromise()

toPromise(): Promise<T>

Defined in: core/ok.ts:725

Converts Result to resolved Promise.

Returns

Promise<T>

Promise resolving to the value

Examples

ts
const value = await Result.ok(42).toPromise()
// 42
ts
// Integrating with Promise-based code
const resultPromise = Result.ok(data).toPromise()

Implementation of

ResultMethods.toPromise


toString()

toString(): string

Defined in: core/ok.ts:742

Converts Result to string representation.

Returns

string

Format "Ok(value)"

Example

ts
Result.ok(42).toString()
// "Ok(42)"

Result.ok({ name: 'John' }).toString()
// "Ok([object Object])"

Implementation of

ResultMethods.toString

Inspecting

contains()

contains(value, comparator?): boolean

Defined in: core/ok.ts:611

Checks if Ok contains specific value.

Uses strict equality (===) by default. Custom comparator allows checking complex objects.

Parameters

value

T

Value to compare

comparator?

(actual, expected) => boolean

Custom comparator

Returns

boolean

true if values match

Examples

ts
Result.ok(42).contains(42) // true
Result.ok(42).contains(99) // false
ts
// With objects (needs comparator)
Result.ok({ id: 1 }).contains(
  { id: 1 },
  (a, b) => a.id === b.id
)
// true

Implementation of

ResultMethods.contains


containsErr()

containsErr(_error, _comparator?): boolean

Defined in: core/ok.ts:626

Checks if Err contains specific error (always false for Ok).

Parameters

_error

E

Error to compare (ignored)

_comparator?

(actual, expected) => boolean

Comparator (ignored)

Returns

boolean

Always false

Example

ts
Result.ok(42).containsErr('fail') // false

Implementation of

ResultMethods.containsErr


inspect()

inspect(visitor): Result<T, E>

Defined in: core/ok.ts:685

Performs side effect on success value.

Useful for logging, debugging, or side effects without breaking chaining.

Parameters

visitor

(value) => void

Side effect function

Returns

Result<T, E>

This instance for chaining

See

Examples

ts
Result.ok(42)
  .inspect((x) => console.log('value:', x))
  .map((x) => x * 2)
// logs "value: 42", returns Ok(84)
ts
// Debug in pipeline
fetchUser(id)
  .inspect((user) => console.log('user loaded'))
  .andThen(validateUser)
  .inspect((user) => console.log('user validated'))

Implementation of

ResultMethods.inspect


inspectErr()

inspectErr(_visitor): Result<T, E>

Defined in: core/ok.ts:703

Performs side effect on error (not applicable for Ok).

Parameters

_visitor

(error) => void

Effect function (ignored)

Returns

Result<T, E>

This instance unchanged

See

inspect for value inspection

Example

ts
Result.ok(42).inspectErr((e) => console.log('error:', e))
// Ok(42) - nothing is logged

Implementation of

ResultMethods.inspectErr


match()

match<L, R>(handlers): L | R

Defined in: core/ok.ts:656

Pattern matching on Result state.

Executes appropriate handler based on state (Ok/Err). Useful for structured handling of both cases.

Type Parameters

L

L

Ok handler return type

R

R

Err handler return type

Parameters

handlers

Handlers for each case

err

(error) => R

ok

(value) => L

Returns

L | R

Result from corresponding handler

Examples

ts
const msg = Result.ok(5).match({
  ok: (x) => `Success: ${x * 2}`,
  err: (e) => `Error: ${e}`
})
// "Success: 10"
ts
// Converting to React component
result.match({
  ok: (user) => <UserProfile user={user} />,
  err: (error) => <ErrorMessage error={error} />,
})

Implementation of

ResultMethods.match

Transforming

filter()

Call Signature

filter(predicate): Result<T, Error>

Defined in: core/ok.ts:379

Filters Ok value based on predicate.

If predicate passes, keeps Ok. If it fails, converts to Err.

Parameters
predicate

(value) => boolean

Validation function

Returns

Result<T, Error>

Ok if passes, Err with default error if fails

See

isOkAnd for validation without modification

Example
ts
Result.ok(10).filter((x) => x > 5)
// Ok(10)

Result.ok(3).filter((x) => x > 5)
// Err(Error: Filter predicate failed for value: 3)
Implementation of

ResultMethods.filter

Call Signature

filter(predicate, onReject): Result<T, E>

Defined in: core/ok.ts:397

Filters Ok value with custom error.

Parameters
predicate

(value) => boolean

Validation function

onReject

(value) => E

Error generator on rejection

Returns

Result<T, E>

Ok if passes, custom Err if fails

Example
ts
Result.ok(3).filter(
  (x) => x > 5,
  (x) => new Error(`${x} is too small`)
)
// Err(Error: 3 is too small)
Implementation of

ResultMethods.filter


flatten()

flatten<U, E2>(this): Result<U, E | E2>

Defined in: core/ok.ts:438

Flattens nested Result.

If Ok contains another Result, extracts the inner Result. Useful for simplifying nested Results.

Type Parameters

U

U

Inner Result value type

E2

E2

Inner Result error type

Parameters

this

Ok<Result<U, E2>, E>

Nested Result

Returns

Result<U, E | E2>

Result with same value, different error type

Throws

If Ok doesn't contain a Result

Examples

ts
Result.ok(Result.ok(42)).flatten()
// Ok(42)

Result.ok(Result.err('fail')).flatten()
// Err("fail")
ts
Result.ok(42).flatten()
// throws Error: flatten() called on Ok that does not contain a Result

Implementation of

ResultMethods.flatten


map()

map<U>(mapper): Result<U, E>

Defined in: core/ok.ts:291

Transforms the success value.

Applies function to value and returns new Ok with result.

Type Parameters

U

U

Transformed value type

Parameters

mapper

(value) => U

Transformation function

Returns

Result<U, E>

Transformed Ok or the original Err

See

  • mapAsync for async version
  • mapOr for default value
  • mapErr to transform the error part (not the value)
  • andThen for automatic flattening of Result returns

Examples

ts
// Simple transformation
Result.ok(5).map((x) => x * 2)
// Ok(10)
ts
// Chaining multiple maps
Result.ok('42')
  .map((s) => parseInt(s, 10))
  .map((n) => n * 2)
// Ok(84)
ts
// On error, map is skipped
Result.err('oops').map((x) => x * 2)
// Err('oops')

Implementation of

ResultMethods.map


mapErr()

mapErr<E2>(_mapper): Result<T, E2>

Defined in: core/ok.ts:356

Transforms the error (not applicable for Ok).

For Ok, keeps the value and only adjusts error type.

Type Parameters

E2

E2

New error type

Parameters

_mapper

(error) => E2

Error transformer (ignored)

Returns

Result<T, E2>

Result with same value, different error type

See

mapErrAsync for async version

Example

ts
Result.ok(42).mapErr((e) => new Error(e))
// Result(42) - type adjusted, but value unchanged

Implementation of

ResultMethods.mapErr


mapOr()

mapOr<U>(mapper, _defaultValue): U

Defined in: core/ok.ts:313

Transforms value or returns default.

For Ok, applies mapper and returns result. For Err, would return the default.

Type Parameters

U

U

Transformed value type

Parameters

mapper

(value) => U

Transformation function

_defaultValue

U

Default value (ignored for Ok)

Returns

U

Transformed value

See

Example

ts
Result.ok(5).mapOr((x) => x * 2, 0) // 10
Result.err('fail').mapOr((x) => x * 2, 0) // 0

Implementation of

ResultMethods.mapOr


mapOrElse()

mapOrElse<U>(okMapper, _errorMapper): U

Defined in: core/ok.ts:337

Transforms value using appropriate mapper.

For Ok, uses success mapper. For Err, would use error mapper.

Type Parameters

U

U

Result type

Parameters

okMapper

(value) => U

Success mapper

_errorMapper

(error) => U

Error mapper (ignored)

Returns

U

Transformed value

See

mapOrElseAsync for async version

Example

ts
Result.ok(5).mapOrElse(
  (x) => x * 2,
  (e) => -1
)
// 10

Implementation of

ResultMethods.mapOrElse