For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/how-to/converting-between-option-and-result.md.

How to convert between Option and Result

To move a value between code that treats "no value" as absence (byenull) and code that treats it as failure (@praha/byethrow), convert at the boundary. toResult turns a None into a Failure you define, while fromResult turns any Failure into a None.

Convert an Option into a Result

To hand an Option to Result-based code, convert it with toResult and provide the error for the None case:

import { 
import Option
Option
} from "byenull";
import {
import Result
Result
} from "@praha/byethrow";
type
type User = {
    id: string;
    name: string;
}
User
= {
id: string
id
: string;
name: string
name
: string };
const
const users: User[]
users
:
type User = {
    id: string;
    name: string;
}
User
[] = [{
id: string
id
: "u1",
name: string
name
: "Alice" }];
const
const findUser: (id: string, users: User[]) => Option.Option<User>
findUser
=
import Option
Option
.
function fn<(id: string, users: User[]) => User | undefined>(fn: (id: string, users: User[]) => User | undefined): (id: string, users: User[]) => Option.Option<User> (+1 overload)

Wraps a function and returns a new function that returns an Option or OptionAsync .

Nullish values and Promise rejections produce None ; synchronous throws are not captured.

@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@example

Synchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);

findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@example

Asynchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});

await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators
fn
((
id: string
id
: string,
users: User[]
users
:
type User = {
    id: string;
    name: string;
}
User
[]) =>
users: User[]
users
.
Array<User>.find(predicate: (value: User, index: number, obj: User[]) => unknown, thisArg?: any): User | undefined (+1 overload)

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

@parampredicate find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
find
((
user: User
user
) =>
user: User
user
.
id: string
id
===
id: string
id
));
const
const result: Result<User, Error>
result
=
import Option
Option
.
function pipe<Option.Option<User>, Result<User, Error>>(a: Option.Option<User>, ab: (a: Option.Option<User>) => Result<User, Error>): Result<User, Error> (+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 25 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 { Option } from 'byenull';

const result = Option.pipe(
  2,
  x => x + 1,
  x => x * 3,
  x => `Result: ${x}`
);
// Result: 9
@categoryUtilities
pipe
(
const findUser: (id: string, users: User[]) => Option.Option<User>
findUser
("u404",
const users: User[]
users
),
import Option
Option
.
function toResult<Error>(err: Error): <O>(option: O) => true extends Option.HasPromise<O> ? ResultAsync<Option.InferSome<O>, Error> : Result<Option.InferSome<O>, Error>

Converts an Option or OptionAsync into a Result from

https://github.com/praha-inc/byethrow @praha/byethrow . A Some becomes a Success; a None becomes a Failure containing err.

@typeParamE - The error type for a Failure.@example

Some Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.some(2),
Option.toResult(new Error('No value')),
);
// { type: 'Success', value: 2 }
@example

None Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.none(),
Option.toResult(new Error('No value')),
);
// { type: 'Failure', error: Error('No value') }
@seefromResult - For the opposite direction.@categoryInterop
toResult
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
("User not found")));
// { type: 'Failure', error: Error('User not found') }

If the error needs context from the call site, build it before converting:

import { 
import Option
Option
} from "byenull";
type
type User = {
    id: string;
    name: string;
}
User
= {
id: string
id
: string;
name: string
name
: string };
declare const
const option: Option.Option<User>
option
:
import Option
Option
.
type Option<T> = Option.Some<T> | Option.None

A union type representing either a Some or a None .

@typeParamT - The type of the Some value.@example
import { Option } from 'byenull';

const doSomething = (): Option.Option<number> => {
  return Math.random() > 0.5
    ? Option.some(10)
    : Option.none();
};
@categoryCore Types
Option
<
type User = {
    id: string;
    name: string;
}
User
>;
const
const result: Result<User, Error>
result
=
import Option
Option
.
function pipe<Option.Option<User>, Result<User, Error>>(a: Option.Option<User>, ab: (a: Option.Option<User>) => Result<User, Error>): Result<User, Error> (+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 25 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 { Option } from 'byenull';

const result = Option.pipe(
  2,
  x => x + 1,
  x => x * 3,
  x => `Result: ${x}`
);
// Result: 9
@categoryUtilities
pipe
(
const option: Option.Option<User>
option
,
import Option
Option
.
function toResult<Error>(err: Error): <O>(option: O) => true extends Option.HasPromise<O> ? ResultAsync<Option.InferSome<O>, Error> : Result<Option.InferSome<O>, Error>

Converts an Option or OptionAsync into a Result from

https://github.com/praha-inc/byethrow @praha/byethrow . A Some becomes a Success; a None becomes a Failure containing err.

@typeParamE - The error type for a Failure.@example

Some Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.some(2),
Option.toResult(new Error('No value')),
);
// { type: 'Success', value: 2 }
@example

None Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.none(),
Option.toResult(new Error('No value')),
);
// { type: 'Failure', error: Error('No value') }
@seefromResult - For the opposite direction.@categoryInterop
toResult
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
("User not found for id u404")));

Convert a Result into an Option

To get an Option back from a Result, use fromResult. A Failure becomes a plain None, and the error is discarded:

import { 
import Option
Option
} from "byenull";
import {
import Result
Result
} from "@praha/byethrow";
type
type User = {
    id: string;
    name: string;
}
User
= {
id: string
id
: string;
name: string
name
: string };
declare const
const result: Result.Result<User, Error>
result
:
import Result
Result
.
type Result<T, E> = Result.Success<T> | Result.Failure<E>

A union type representing either a success or a failure.

@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
import { Result } from '@praha/byethrow';

const doSomething = (): Result.Result<number, string> => {
  return Math.random() > 0.5
    ? { type: 'Success', value: 10 }
    : { type: 'Failure', error: 'Oops' };
};
@categoryCore Types
Result
<
type User = {
    id: string;
    name: string;
}
User
, Error>;
const
const option: Option.Option<User>
option
=
import Option
Option
.
function fromResult<User>(result: Result<User, any>): Option.Option<User> (+1 overload)

Converts a Result from

https://github.com/praha-inc/byethrow @praha/byethrow into an

Option or OptionAsync . A Success becomes a Some ; a Failure becomes a None , discarding the error.

@typeParamT - The success value type.@example

Success Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.succeed(2));
// { type: 'Some', value: 2 }
@example

Failure Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.fail(new Error('Something went wrong')));
// { type: 'None' }
@seetoResult - For the opposite direction.@categoryInterop
fromResult
(
const result: Result.Result<User, Error>
result
);
// Some<User> or None

If the error carries information you still need, recover it with byethrow first and convert the outcome:

import { 
import Option
Option
} from "byenull";
import {
import Result
Result
} from "@praha/byethrow";
type
type User = {
    id: string;
    name: string;
}
User
= {
id: string
id
: string;
name: string
name
: string };
declare const
const result: Result.Result<User, Error>
result
:
import Result
Result
.
type Result<T, E> = Result.Success<T> | Result.Failure<E>

A union type representing either a success or a failure.

@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
import { Result } from '@praha/byethrow';

const doSomething = (): Result.Result<number, string> => {
  return Math.random() > 0.5
    ? { type: 'Success', value: 10 }
    : { type: 'Failure', error: 'Oops' };
};
@categoryCore Types
Result
<
type User = {
    id: string;
    name: string;
}
User
, Error>;
declare const
const fallbackUser: User
fallbackUser
:
type User = {
    id: string;
    name: string;
}
User
;
const
const option: Option.Option<User>
option
=
import Option
Option
.
function fromResult<User>(result: Result<User, any>): Option.Option<User> (+1 overload)

Converts a Result from

https://github.com/praha-inc/byethrow @praha/byethrow into an

Option or OptionAsync . A Success becomes a Some ; a Failure becomes a None , discarding the error.

@typeParamT - The success value type.@example

Success Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.succeed(2));
// { type: 'Some', value: 2 }
@example

Failure Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.fail(new Error('Something went wrong')));
// { type: 'None' }
@seetoResult - For the opposite direction.@categoryInterop
fromResult
(
import Result
Result
.
function pipe<Result.Result<User, Error>, Result.Result<User, never>>(a: Result.Result<User, Error>, ab: (a: Result.Result<User, Error>) => Result.Result<User, never>): Result.Result<User, never> (+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 result: Result.Result<User, Error>
result
,
import Result
Result
.
function orElse<Result.Result<User, Error>, Result.Result<User, never>>(fn: (a: Error) => Result.Result<User, never>): (result: Result.Result<User, Error>) => Result.Result<User, never> (+1 overload)

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

@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(42),
Result.orElse((error) => Result.succeed(0)),
);
// { type: 'Success', value: 42 }
@example

Failure Case (function returns a Success)

import { Result } from '@praha/byethrow';

const result = Result.pipe(
Result.fail('original error'),
Result.orElse((error) => Result.succeed('default value')),
);
// result: { type: 'Success', value: 'default value' }
@example

Failure Case (function returns a Failure)

import { Result } from '@praha/byethrow';

const result = Result.pipe(
Result.fail('original error'),
Result.orElse((error) => Result.fail('new error: ' + error)),
);
// result: { type: 'Failure', error: 'new error: original error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
orElse
(() =>
import Result
Result
.
function succeed<User>(value: User): Result.Result<User, never> (+1 overload)

Creates a Success result from a given value.

Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

Synchronous Usage

import { Result } from '@praha/byethrow';

const result = Result.succeed(42);
// Result.Result<42, never>
@example

With No Value

import { Result } from '@praha/byethrow';

const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
succeed
(
const fallbackUser: User
fallbackUser
)),
), ); // Some<User>, the fallback when the original Result failed

Convert asynchronous values

Both converters handle OptionAsync and ResultAsync the same way, and the result is asynchronous:

import { 
import Option
Option
} from "byenull";
import {
import Result
Result
} from "@praha/byethrow";
const
const result: Result<number, string>
result
= await
import Option
Option
.
function toResult<string>(err: string): <O>(option: O) => true extends Option.HasPromise<O> ? ResultAsync<Option.InferSome<O>, string> : Result<Option.InferSome<O>, string>

Converts an Option or OptionAsync into a Result from

https://github.com/praha-inc/byethrow @praha/byethrow . A Some becomes a Success; a None becomes a Failure containing err.

@typeParamE - The error type for a Failure.@example

Some Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.some(2),
Option.toResult(new Error('No value')),
);
// { type: 'Success', value: 2 }
@example

None Case

import { Option } from 'byenull';

const result = Option.pipe(
Option.none(),
Option.toResult(new Error('No value')),
);
// { type: 'Failure', error: Error('No value') }
@seefromResult - For the opposite direction.@categoryInterop
toResult
("No value")(
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<Option.Option<number>>(value: Option.Option<number>): Promise<Option.Option<number>> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.@returnsA promise whose internal state matches the provided promise.
resolve
(
import Option
Option
.
function some<number>(value: number): Option.Option<number>

Creates a Some from a given value. Passing null or undefined returns None instead.

@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@example
import { Option } from 'byenull';

const some = Option.some(42);
// { type: 'Some', value: 42 }

const none = Option.some(null);
// { type: 'None' }
@categoryCreators
some
(2)));
// { type: 'Success', value: 2 }, a ResultAsync resolved to a Result const
const option: Option.Option<2>
option
= await
import Option
Option
.
function fromResult<2>(result: ResultAsync<2, any>): Option.OptionAsync<2> (+1 overload)

Converts a Result from

https://github.com/praha-inc/byethrow @praha/byethrow into an

Option or OptionAsync . A Success becomes a Some ; a Failure becomes a None , discarding the error.

@typeParamT - The success value type.@example

Success Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.succeed(2));
// { type: 'Some', value: 2 }
@example

Failure Case

import { Option } from 'byenull';
import { Result } from '@praha/byethrow';

const option = Option.fromResult(Result.fail(new Error('Something went wrong')));
// { type: 'None' }
@seetoResult - For the opposite direction.@categoryInterop
fromResult
(
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<Result.Result<2, never>>(value: Result.Result<2, never>): Promise<Result.Result<2, never>> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.@returnsA promise whose internal state matches the provided promise.
resolve
(
import Result
Result
.
function succeed<2>(value: 2): Result.Result<2, never> (+1 overload)

Creates a Success result from a given value.

Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

Synchronous Usage

import { Result } from '@praha/byethrow';

const result = Result.succeed(42);
// Result.Result<42, never>
@example

With No Value

import { Result } from '@praha/byethrow';

const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
succeed
(2)));
// { type: 'Some', value: 2 }

Where to convert from one to another

To keep conversions rare, apply the rule of thumb: convert where the meaning changes. Looking up a user with an Option can be fine if you can work with a nullable value. If "user not found" becomes an error in your system, convert to a Result or use a Result in the first place. For the reasoning behind the split, see Option vs Result.

In general conversions from Result happen more often than conversions to Result. If you find yourself converting from Result to Option a lot, your system is probably silently dropping relevant errors.