Skip to content

Effect vs neverthrow

When working with error handling in TypeScript, both neverthrow and Effect provide useful abstractions for modeling success and failure without exceptions. They share many concepts, such as wrapping computations in a safe container, transforming values with map, handling errors with mapErr/mapLeft, and offering utilities to combine or unwrap results.

This page shows a side-by-side comparison of neverthrow and Effect APIs for common use cases. If you’re already familiar with neverthrow, the examples will help you understand how to achieve the same patterns with Effect. If you’re starting fresh, the comparison highlights the similarities and differences so you can decide which library better fits your project.

neverthrow exposes instance methods (for example, result.map(...)). Effect exposes functions on Either (for example, Either.map(result, ...)) and supports a pipe style for readability and better tree shaking.

Example (Creating a success result)

import {
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
} from "neverthrow"
const
const result: Ok<{
myData: string;
}, never>
result
=
ok<{
myData: string;
}, never>(value: {
myData: string;
}): Ok<{
myData: string;
}, never> (+1 overload)
ok
({
myData: string
myData
: "test" })
const result: Ok<{
myData: string;
}, never>
result
.
Ok<{ myData: string; }, never>.isOk(): this is Ok<{
myData: string;
}, never>

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
() // true
const result: Ok<{
myData: string;
}, never>
result
.
Ok<{ myData: string; }, never>.isErr(): this is Err<{
myData: string;
}, never>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
() // false

Example (Creating a failure result)

import {
function err<T = never, E extends string = string>(err: E): Err<T, E> (+2 overloads)
err
} from "neverthrow"
const
const result: Err<never, "Oh no">
result
=
err<never, "Oh no">(err: "Oh no"): Err<never, "Oh no"> (+2 overloads)
err
("Oh no")
const result: Err<never, "Oh no">
result
.
Err<never, "Oh no">.isOk(): this is Ok<never, "Oh no">

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
() // false
const result: Err<never, "Oh no">
result
.
Err<never, "Oh no">.isErr(): this is Err<never, "Oh no">

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
() // true

Example (Transforming the success value)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
} from "neverthrow"
declare function
function getLines(s: string): Result<Array<string>, Error>
getLines
(
s: string
s
: string):
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<
interface Array<T>
Array
<string>,
interface Error
Error
>
const
const result: Result<string[], Error>
result
=
function getLines(s: string): Result<Array<string>, Error>
getLines
("1\n2\n3\n4\n")
// this Result now has a Array<number> inside it
const
const newResult: Result<number[], Error>
newResult
=
const result: Result<string[], Error>
result
.
map<number[]>(f: (t: string[]) => number[]): Result<number[], Error>

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

@paramf The function to apply an OK value

@returnsthe result of applying f or an Err untouched

map
((
arr: string[]
arr
) =>
arr: string[]
arr
.
Array<string>.map<number>(callbackfn: (value: string, index: number, array: string[]) => number, thisArg?: any): number[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(
function parseInt(string: string, radix?: number): number

Converts a string to an integer.

@paramstring A string to convert into a number.

@paramradix A value between 2 and 36 that specifies the base of the number in string. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.

parseInt
))
const newResult: Result<number[], Error>
newResult
.
function isOk(): this is Ok<T, E>

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
() // true

Example (Transforming the error value)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
} from "neverthrow"
declare function
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string
):
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, string>, string>
const
const rawHeaders: "nonsensical gibberish and badly formatted stuff"
rawHeaders
= "nonsensical gibberish and badly formatted stuff"
const
const result: Result<Record<string, string>, string>
result
=
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
const rawHeaders: "nonsensical gibberish and badly formatted stuff"
rawHeaders
)
// const newResult: Result<Record<string, string>, Error>
const
const newResult: Result<Record<string, string>, Error>
newResult
=
const result: Result<Record<string, string>, string>
result
.
mapErr<Error>(_f: (e: string) => Error): Result<Record<string, string>, Error>

Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

This function can be used to pass through a successful result while handling an error.

@paramf a function to apply to the error Err value

mapErr
((
err: string
err
) => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
(
err: string
err
))

Example (Providing a default value)

import {
function err<T = never, E extends string = string>(err: E): Err<T, E> (+2 overloads)
err
} from "neverthrow"
const
const result: Err<never, "Oh no">
result
=
err<never, "Oh no">(err: "Oh no"): Err<never, "Oh no"> (+2 overloads)
err
("Oh no")
const
const multiply: (value: number) => number
multiply
= (
value: number
value
: number): number =>
value: number
value
* 2
const
const unwrapped: number
unwrapped
=
const result: Err<never, "Oh no">
result
.
Err<never, "Oh no">.map<number>(_f: (t: never) => number): Result<number, "Oh no">

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

@paramf The function to apply an OK value

@returnsthe result of applying f or an Err untouched

map
(
const multiply: (value: number) => number
multiply
).
unwrapOr<10>(_v: 10): number

Unwrap the Ok value, or return the default if there is an Err

@paramv the default value to return if there is an Err

unwrapOr
(10)

Example (Chaining computations that may fail)

import {
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
,
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
function err<T = never, E extends string = string>(err: E): Err<T, E> (+2 overloads)
err
} from "neverthrow"
const
const sqrt: (n: number) => Result<number, string>
sqrt
= (
n: number
n
: number):
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string> =>
n: number
n
> 0 ?
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.sqrt(x: number): number

Returns the square root of a number.

@paramx A numeric expression.

sqrt
(
n: number
n
)) :
err<number, "n must be positive">(err: "n must be positive"): Err<number, "n must be positive"> (+2 overloads)
err
("n must be positive")
ok<number, never>(value: number): Ok<number, never> (+1 overload)
ok
(16).
Ok<number, never>.andThen<Result<number, string>>(f: (t: number) => Result<number, string>): Result<number, string> (+1 overload)

Similar to map Except you must return a new Result.

This is useful for when you need to do a subsequent computation using the inner T value, but that computation might fail. Additionally, andThen is really useful as a tool to flatten a Result<Result<A, E2>, E1> into a Result<A, E2> (see example below).

andThen
(
const sqrt: (n: number) => Result<number, string>
sqrt
).
andThen<Result<number, string>>(f: (t: number) => Result<number, string>): Result<number, string> (+1 overload)

Similar to map Except you must return a new Result.

This is useful for when you need to do a subsequent computation using the inner T value, but that computation might fail. Additionally, andThen is really useful as a tool to flatten a Result<Result<A, E2>, E1> into a Result<A, E2> (see example below).

andThen
(
const sqrt: (n: number) => Result<number, string>
sqrt
)
// Ok(2)

Example (Chaining asynchronous computations that may fail)

import {
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
,
function okAsync<T, E = never>(value: T): ResultAsync<T, E> (+1 overload)
okAsync
} from "neverthrow"
// const result: ResultAsync<number, never>
const
const result: ResultAsync<number, never>
result
=
ok<number, never>(value: number): Ok<number, never> (+1 overload)
ok
(1).
Ok<number, never>.asyncAndThen<number, never>(f: (t: number) => ResultAsync<number, never>): ResultAsync<number, never>

Similar to map Except you must return a new Result.

This is useful for when you need to do a subsequent async computation using the inner T value, but that computation might fail. Must return a ResultAsync

@paramf The function that returns a ResultAsync to apply to the current value

asyncAndThen
((
n: number
n
) =>
okAsync<number, never>(value: number): ResultAsync<number, never> (+1 overload)
okAsync
(
n: number
n
+ 1))

Example (Providing an alternative on failure)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
function err<T = never, E extends string = string>(err: E): Err<T, E> (+2 overloads)
err
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
} from "neverthrow"
enum
enum DatabaseError
DatabaseError
{
function (enum member) DatabaseError.PoolExhausted = "PoolExhausted"
PoolExhausted
= "PoolExhausted",
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
= "NotFound"
}
const
const dbQueryResult: Result<string, DatabaseError>
dbQueryResult
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<string,
enum DatabaseError
DatabaseError
> =
err<string, DatabaseError.NotFound>(err: DatabaseError.NotFound): Err<string, DatabaseError.NotFound> (+2 overloads)
err
(
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
)
const
const updatedQueryResult: Result<string, number>
updatedQueryResult
=
const dbQueryResult: Err<string, DatabaseError>
dbQueryResult
.
Err<string, DatabaseError>.orElse<Ok<string, never> | Err<never, number>>(f: (e: DatabaseError) => Ok<string, never> | Err<never, number>): Result<string, number> (+1 overload)

Takes an Err value and maps it to a Result<T, SomeNewType>.

This is useful for error recovery.

orElse
((
dbError: DatabaseError
dbError
) =>
dbError: DatabaseError
dbError
===
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
?
ok<string, never>(value: string): Ok<string, never> (+1 overload)
ok
("User does not exist")
:
err<never, number>(err: number): Err<never, number> (+2 overloads)
err
(500)
)

Example (Pattern matching on success or failure)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
} from "neverthrow"
declare const
const myResult: Result<number, string>
myResult
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string>
const myResult: Result<number, string>
myResult
.
match<string, string>(ok: (t: number) => string, _err: (e: string) => string): string

Given 2 functions (one for the Ok variant and one for the Err variant) execute the function that matches the Result variant.

Match callbacks do not necessitate to return a Result, however you can return a Result if you want to.

match is like chaining map and mapErr, with the distinction that with match both functions must have the same return type.

@paramok

@paramerr

match
(
(
value: number
value
) => `The value is ${
value: number
value
}`,
(
error: string
error
) => `The error is ${
error: string
error
}`
)

Example (Parsing headers and looking up a user)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
} from "neverthrow"
interface
interface User
User
{}
declare function
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string
):
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, string>, string>
declare function
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(
authorization: string
authorization
: string
):
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface User
User
| undefined>
const
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
= "Authorization: Bearer 1234567890"
// const asyncResult: ResultAsync<User | undefined, string>
const
const asyncResult: ResultAsync<User | undefined, string>
asyncResult
=
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
)
.
map<string>(f: (t: Record<string, string>) => string): Result<string, string>

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

@paramf The function to apply an OK value

@returnsthe result of applying f or an Err untouched

map
((
kvMap: Record<string, string>
kvMap
) =>
kvMap: Record<string, string>
kvMap
["Authorization"])
.
asyncMap<User | undefined>(f: (t: string) => Promise<User | undefined>): ResultAsync<User | undefined, string>

Maps a Result<T, E> to ResultAsync<U, E> by applying an async function to a contained Ok value, leaving an Err value untouched.

@paramf An async function to apply an OK value

asyncMap
((
authorization: string
authorization
) =>
authorization: string
authorization
===
var undefined
undefined
?
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

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

Creates a new resolved promise for the provided value.

@paramvalue A promise.

@returnsA promise whose internal state matches the provided promise.

resolve
(
var undefined
undefined
)
:
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(
authorization: string
authorization
)
)

Example (Combining multiple results)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
} from "neverthrow"
const
const results: Result<number, string>[]
results
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string>[] = [
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(1),
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(2)]
// const combined: Result<number[], string>
const
const combined: Result<number[], string>
combined
=
(alias) namespace Result
import Result
Result
.
function Result<T, E>.combine<Result<number, string>[]>(resultList: Result<number, string>[]): Result<number[], string> (+1 overload)
combine
(
const results: Result<number, string>[]
results
)

Example (Collecting all errors and successes)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
,
function err<T = never, E extends string = string>(err: E): Err<T, E> (+2 overloads)
err
} from "neverthrow"
const
const results: Result<number, string>[]
results
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string>[] = [
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(123),
err<number, "boooom!">(err: "boooom!"): Err<number, "boooom!"> (+2 overloads)
err
("boooom!"),
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(456),
err<number, "ahhhhh!">(err: "ahhhhh!"): Err<number, "ahhhhh!"> (+2 overloads)
err
("ahhhhh!")
]
const
const result: Result<number[], string[]>
result
=
(alias) namespace Result
import Result
Result
.
function Result<T, E>.combineWithAllErrors<Result<number, string>[]>(resultList: Result<number, string>[]): Result<number[], string[]> (+1 overload)
combineWithAllErrors
(
const results: Result<number, string>[]
results
)
// result is Err(['boooom!', 'ahhhhh!'])

Note. There is no exact equivalent of Result.combineWithAllErrors in Effect. Use Array.getLefts to collect all errors and Array.getRights to collect all successes.

In the examples below we use Effect.runPromise to run an effect and return a Promise. You can also use other APIs such as Effect.runPromiseExit, which can capture additional cases like defects (runtime errors) and interruptions.

Example (Creating a successful async result)

import {
function okAsync<T, E = never>(value: T): ResultAsync<T, E> (+1 overload)
okAsync
} from "neverthrow"
const
const myResultAsync: ResultAsync<{
myData: string;
}, never>
myResultAsync
=
okAsync<{
myData: string;
}, never>(value: {
myData: string;
}): ResultAsync<{
myData: string;
}, never> (+1 overload)
okAsync
({
myData: string
myData
: "test" })
const
const result: Result<{
myData: string;
}, never>
result
= await
const myResultAsync: ResultAsync<{
myData: string;
}, never>
myResultAsync
const result: Result<{
myData: string;
}, never>
result
.
function isOk(): this is Ok<T, E>

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
() // true
const result: Result<{
myData: string;
}, never>
result
.
function isErr(): this is Err<T, E>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
() // false

Example (Creating a failed async result)

import {
function errAsync<T = never, E = unknown>(err: E): ResultAsync<T, E> (+1 overload)
errAsync
} from "neverthrow"
const
const myResultAsync: ResultAsync<never, string>
myResultAsync
=
errAsync<never, string>(err: string): ResultAsync<never, string> (+1 overload)
errAsync
("Oh no")
const
const myResult: Result<never, string>
myResult
= await
const myResultAsync: ResultAsync<never, string>
myResultAsync
const myResult: Result<never, string>
myResult
.
function isOk(): this is Ok<T, E>

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
() // false
const myResult: Result<never, string>
myResult
.
function isErr(): this is Err<T, E>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
() // true

Example (Wrapping a Promise-returning function that may throw)

import {
class ResultAsync<T, E>
ResultAsync
} from "neverthrow"
interface
interface User
User
{}
declare function
function insertIntoDb(user: User): Promise<User>
insertIntoDb
(
user: User
user
:
interface User
User
):
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface User
User
>
// (user: User) => ResultAsync<User, Error>
const
const insertUser: (user: User) => ResultAsync<User, Error>
insertUser
=
class ResultAsync<T, E>
ResultAsync
.
ResultAsync<T, E>.fromThrowable<[user: User], User, Error>(fn: (user: User) => Promise<User>, errorFn?: ((err: unknown) => Error) | undefined): (user: User) => ResultAsync<User, Error>
fromThrowable
(
function insertIntoDb(user: User): Promise<User>
insertIntoDb
,
() => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Database error")
)

Example (Transforming the success value)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
class ResultAsync<T, E>
ResultAsync
} from "neverthrow"
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function findUsersIn(country: string): ResultAsync<Array<User>, Error>
findUsersIn
(
country: string
country
: string
):
class ResultAsync<T, E>
ResultAsync
<
interface Array<T>
Array
<
interface User
User
>,
interface Error
Error
>
const
const usersInCanada: ResultAsync<User[], Error>
usersInCanada
=
function findUsersIn(country: string): ResultAsync<Array<User>, Error>
findUsersIn
("Canada")
const
const namesInCanada: ResultAsync<string[], Error>
namesInCanada
=
const usersInCanada: ResultAsync<User[], Error>
usersInCanada
.
ResultAsync<User[], Error>.map<string[]>(f: (t: User[]) => string[] | Promise<string[]>): ResultAsync<string[], Error>
map
((
users: User[]
users
:
interface Array<T>
Array
<
interface User
User
>) =>
users: User[]
users
.
Array<User>.map<string>(callbackfn: (value: User, index: number, array: User[]) => string, thisArg?: any): string[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
user: User
user
) =>
user: User
user
.
User.name: string
name
)
)
// We can extract the Result using .then() or await
const namesInCanada: ResultAsync<string[], Error>
namesInCanada
.
ResultAsync<string[], Error>.then<void, unknown>(successCallback?: ((res: Result<string[], Error>) => void | PromiseLike<void>) | undefined, failureCallback?: ((reason: unknown) => unknown) | undefined): PromiseLike<unknown>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
((
namesResult: Result<string[], Error>
namesResult
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<
interface Array<T>
Array
<string>,
interface Error
Error
>) => {
if (
namesResult: Result<string[], Error>
namesResult
.
function isErr(): this is Err<T, E>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
()) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
"Couldn't get the users from the database",
namesResult: Err<string[], Error>
namesResult
.
Err<string[], Error>.error: Error
error
)
} else {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
"Users in Canada are named: " +
namesResult: Ok<string[], Error>
namesResult
.
Ok<string[], Error>.value: string[]
value
.
Array<string>.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

@paramseparator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

join
(",")
)
}
})

Example (Transforming the error value)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
class ResultAsync<T, E>
ResultAsync
} from "neverthrow"
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function findUsersIn(country: string): ResultAsync<Array<User>, Error>
findUsersIn
(
country: string
country
: string
):
class ResultAsync<T, E>
ResultAsync
<
interface Array<T>
Array
<
interface User
User
>,
interface Error
Error
>
const
const usersInCanada: ResultAsync<User[], "Unknown country" | "System error, please contact an administrator.">
usersInCanada
=
function findUsersIn(country: string): ResultAsync<Array<User>, Error>
findUsersIn
("Canada").
ResultAsync<User[], Error>.mapErr<"Unknown country" | "System error, please contact an administrator.">(f: (e: Error) => "Unknown country" | "System error, please contact an administrator." | Promise<"Unknown country" | "System error, please contact an administrator.">): ResultAsync<User[], "Unknown country" | "System error, please contact an administrator.">
mapErr
((
error: Error
error
:
interface Error
Error
) => {
// The only error we want to pass to the user is "Unknown country"
if (
error: Error
error
.
Error.message: string
message
=== "Unknown country") {
return
error: Error
error
.
Error.message: "Unknown country"
message
}
// All other errors will be labelled as a system error
return "System error, please contact an administrator."
})
const usersInCanada: ResultAsync<User[], "Unknown country" | "System error, please contact an administrator.">
usersInCanada
.
ResultAsync<User[], "Unknown country" | "System error, please contact an administrator.">.then<void, unknown>(successCallback?: ((res: Result<User[], "Unknown country" | "System error, please contact an administrator.">) => void | PromiseLike<void>) | undefined, failureCallback?: ((reason: unknown) => unknown) | undefined): PromiseLike<unknown>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
((
usersResult: Result<User[], string>
usersResult
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<
interface Array<T>
Array
<
interface User
User
>, string>) => {
if (
usersResult: Result<User[], string>
usersResult
.
function isErr(): this is Err<T, E>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
()) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
"Couldn't get the users from the database",
usersResult: Err<User[], string>
usersResult
.
Err<User[], string>.error: string
error
)
} else {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
("Users in Canada are: " +
usersResult: Ok<User[], string>
usersResult
.
Ok<User[], string>.value: User[]
value
.
Array<User>.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

@paramseparator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

join
(","))
}
})

Example (Providing a default value when async fails)

import {
function errAsync<T = never, E = unknown>(err: E): ResultAsync<T, E> (+1 overload)
errAsync
} from "neverthrow"
const
const unwrapped: number
unwrapped
= await
errAsync<never, number>(err: number): ResultAsync<never, number> (+1 overload)
errAsync
(0).
ResultAsync<never, number>.unwrapOr<number>(t: number): Promise<number>
unwrapOr
(10)
// unwrapped = 10

Example (Chaining multiple async computations)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
class ResultAsync<T, E>
ResultAsync
} from "neverthrow"
interface
interface User
User
{}
declare function
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
user: User
user
:
interface User
User
):
class ResultAsync<T, E>
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): ResultAsync<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
class ResultAsync<T, E>
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function sendNotification(user: User): ResultAsync<void, Error>
sendNotification
(
user: User
user
:
interface User
User
):
class ResultAsync<T, E>
ResultAsync
<void,
interface Error
Error
>
const
const user: User
user
:
interface User
User
= {}
const
const resAsync: ResultAsync<void, Error>
resAsync
=
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
const user: User
user
)
.
ResultAsync<User, Error>.andThen<ResultAsync<User, Error>>(f: (t: User) => ResultAsync<User, Error>): ResultAsync<User, Error> (+2 overloads)
andThen
(
function insertUser(user: User): ResultAsync<User, Error>
insertUser
)
.
ResultAsync<User, Error>.andThen<ResultAsync<void, Error>>(f: (t: User) => ResultAsync<void, Error>): ResultAsync<void, Error> (+2 overloads)
andThen
(
function sendNotification(user: User): ResultAsync<void, Error>
sendNotification
)
const resAsync: ResultAsync<void, Error>
resAsync
.
ResultAsync<void, Error>.then<void, unknown>(successCallback?: ((res: Result<void, Error>) => void | PromiseLike<void>) | undefined, failureCallback?: ((reason: unknown) => unknown) | undefined): PromiseLike<unknown>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
((
res: Result<void, Error>
res
:
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<void,
interface Error
Error
>) => {
if (
res: Result<void, Error>
res
.
function isErr(): this is Err<T, E>

Used to check if a Result is an Err

@returnstrue if the result is an Err variant of Result

isErr
()) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
("Oops, at least one step failed",
res: Err<void, Error>
res
.
Err<void, Error>.error: Error
error
)
} else {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
"User has been validated, inserted and notified successfully."
)
}
})

Example (Fallback when an async operation fails)

import {
class ResultAsync<T, E>
ResultAsync
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
} from "neverthrow"
interface
interface User
User
{}
declare function
function fetchUserData(id: string): ResultAsync<User, Error>
fetchUserData
(
id: string
id
: string):
class ResultAsync<T, E>
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function getDefaultUser(): User
getDefaultUser
():
interface User
User
const
const userId: "123"
userId
= "123"
// Try to fetch user data, but provide a default if it fails
const
const userResult: ResultAsync<User, never>
userResult
=
function fetchUserData(id: string): ResultAsync<User, Error>
fetchUserData
(
const userId: "123"
userId
).
ResultAsync<User, Error>.orElse<Ok<User, never>>(f: (e: Error) => Ok<User, never>): ResultAsync<User, never> (+2 overloads)
orElse
(() =>
ok<User, never>(value: User): Ok<User, never> (+1 overload)
ok
(
function getDefaultUser(): User
getDefaultUser
())
)
const userResult: ResultAsync<User, never>
userResult
.
ResultAsync<User, never>.then<void, unknown>(successCallback?: ((res: Result<User, never>) => void | PromiseLike<void>) | undefined, failureCallback?: ((reason: unknown) => unknown) | undefined): PromiseLike<unknown>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
((
result: Result<User, never>
result
) => {
if (
result: Result<User, never>
result
.
function isOk(): this is Ok<T, E>

Used to check if a Result is an OK

@returnstrue if the result is an OK variant of Result

isOk
()) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
("User data:",
result: Ok<User, never>
result
.
Ok<User, never>.value: User
value
)
}
})

Example (Handling success and failure at the end of a chain)

import {
class ResultAsync<T, E>
ResultAsync
} from "neverthrow"
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
user: User
user
:
interface User
User
):
class ResultAsync<T, E>
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): ResultAsync<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
class ResultAsync<T, E>
ResultAsync
<
interface User
User
,
interface Error
Error
>
const
const user: User
user
:
interface User
User
= {
User.name: string
name
: "John" }
// Handle both cases at the end of the chain using match
const
const resultMessage: string
resultMessage
= await
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
const user: User
user
)
.
ResultAsync<User, Error>.andThen<ResultAsync<User, Error>>(f: (t: User) => ResultAsync<User, Error>): ResultAsync<User, Error> (+2 overloads)
andThen
(
function insertUser(user: User): ResultAsync<User, Error>
insertUser
)
.
ResultAsync<User, Error>.match<string, string>(ok: (t: User) => string, _err: (e: Error) => string): Promise<string>
match
(
(
user: User
user
:
interface User
User
) => `User ${
user: User
user
.
User.name: string
name
} has been successfully created`,
(
error: Error
error
:
interface Error
Error
) => `User could not be created because ${
error: Error
error
.
Error.message: string
message
}`
)

Example (Combining multiple async results)

import {
class ResultAsync<T, E>
ResultAsync
,
function okAsync<T, E = never>(value: T): ResultAsync<T, E> (+1 overload)
okAsync
} from "neverthrow"
const
const resultList: ResultAsync<number, string>[]
resultList
:
class ResultAsync<T, E>
ResultAsync
<number, string>[] = [
okAsync<number, string>(value: number): ResultAsync<number, string> (+1 overload)
okAsync
(1),
okAsync<number, string>(value: number): ResultAsync<number, string> (+1 overload)
okAsync
(2)]
// const combinedList: ResultAsync<number[], string>
const
const combinedList: ResultAsync<number[], string>
combinedList
=
class ResultAsync<T, E>
ResultAsync
.
ResultAsync<T, E>.combine<ResultAsync<number, string>[]>(asyncResultList: ResultAsync<number, string>[]): ResultAsync<number[], string> (+1 overload)
combine
(
const resultList: ResultAsync<number, string>[]
resultList
)

Example (Collecting all errors instead of failing fast)

import {
class ResultAsync<T, E>
ResultAsync
,
function okAsync<T, E = never>(value: T): ResultAsync<T, E> (+1 overload)
okAsync
,
function errAsync<T = never, E = unknown>(err: E): ResultAsync<T, E> (+1 overload)
errAsync
} from "neverthrow"
const
const resultList: ResultAsync<number, string>[]
resultList
:
class ResultAsync<T, E>
ResultAsync
<number, string>[] = [
okAsync<number, string>(value: number): ResultAsync<number, string> (+1 overload)
okAsync
(123),
errAsync<number, string>(err: string): ResultAsync<number, string> (+1 overload)
errAsync
("boooom!"),
okAsync<number, string>(value: number): ResultAsync<number, string> (+1 overload)
okAsync
(456),
errAsync<number, string>(err: string): ResultAsync<number, string> (+1 overload)
errAsync
("ahhhhh!")
]
const
const result: Result<number[], string[]>
result
= await
class ResultAsync<T, E>
ResultAsync
.
ResultAsync<T, E>.combineWithAllErrors<ResultAsync<number, string>[]>(asyncResultList: ResultAsync<number, string>[]): ResultAsync<number[], string[]> (+1 overload)
combineWithAllErrors
(
const resultList: ResultAsync<number, string>[]
resultList
)
// result is Err(['boooom!', 'ahhhhh!'])

Example (Safely wrapping a throwing function)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
} from "neverthrow"
type
type ParseError = {
message: string;
}
ParseError
= {
message: string
message
: string }
const
const toParseError: () => ParseError
toParseError
= ():
type ParseError = {
message: string;
}
ParseError
=> ({
message: string
message
: "Parse Error" })
const
const safeJsonParse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => Result<any, ParseError>
safeJsonParse
=
(alias) namespace Result
import Result
Result
.
function Result<T, E>.fromThrowable<(text: string, reviver?: (this: any, key: string, value: any) => any) => any, ParseError>(fn: (text: string, reviver?: (this: any, key: string, value: any) => any) => any, errorFn?: ((e: unknown) => ParseError) | undefined): (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => Result<any, ParseError>

Wraps a function with a try catch, creating a new function with the same arguments but returning Ok if successful, Err if the function throws

@paramfn function to wrap with ok on success or err on failure

@paramerrorFn when an error is thrown, this will wrap the error result if provided

fromThrowable
(
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
,
const toParseError: () => ParseError
toParseError
)
// the function can now be used safely,
// if the function throws, the result will be an Err
const
const result: Result<any, ParseError>
result
=
const safeJsonParse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => Result<any, ParseError>
safeJsonParse
("{")

Example (Using generators to simplify error handling)

import {
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
,
function safeTry<T, E>(body: () => Generator<Err<never, E>, Result<T, E>>): Result<T, E> (+3 overloads)

Evaluates the given generator to a Result returned or an Err yielded from it, whichever comes first.

This function is intended to emulate Rust's ? operator. See /tests/safeTry.test.ts for examples.

@parambody - What is evaluated. In body, yield* result works as Rust's result? expression.

@returnsThe first occurrence of either an yielded Err or a returned Result.

safeTry
} from "neverthrow"
declare function
function mayFail1(): Result<number, string>
mayFail1
():
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string>
declare function
function mayFail2(): Result<number, string>
mayFail2
():
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string>
function
function myFunc(): Result<number, string>
myFunc
():
type Result<T, E> = Ok<T, E> | Err<T, E>
Result
<number, string> {
return
safeTry<number, string>(body: () => Generator<Err<never, string>, Result<number, string>, any>): Result<number, string> (+3 overloads)

Evaluates the given generator to a Result returned or an Err yielded from it, whichever comes first.

This function is intended to emulate Rust's ? operator. See /tests/safeTry.test.ts for examples.

@parambody - What is evaluated. In body, yield* result works as Rust's result? expression.

@returnsThe first occurrence of either an yielded Err or a returned Result.

safeTry
<number, string>(function* () {
return
ok<number, string>(value: number): Ok<number, string> (+1 overload)
ok
(
(yield*
function mayFail1(): Result<number, string>
mayFail1
().
mapErr<string>(_f: (e: string) => string): Result<number, string>

Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

This function can be used to pass through a successful result while handling an error.

@paramf a function to apply to the error Err value

mapErr
(
(
e: string
e
) => `aborted by an error from 1st function, ${
e: string
e
}`
)) +
(yield*
function mayFail2(): Result<number, string>
mayFail2
().
mapErr<string>(_f: (e: string) => string): Result<number, string>

Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

This function can be used to pass through a successful result while handling an error.

@paramf a function to apply to the error Err value

mapErr
(
(
e: string
e
) => `aborted by an error from 2nd function, ${
e: string
e
}`
))
)
})
}

Note. With Either.gen, you do not need to wrap the final value with Either.right. The generator’s return value becomes the Right.

You can also use an async generator function with safeTry to represent an asynchronous block. On the Effect side, the same pattern is written with Effect.gen instead of Either.gen.

Example (Using async generators to handle multiple failures)

import {
class ResultAsync<T, E>
ResultAsync
,
function safeTry<T, E>(body: () => Generator<Err<never, E>, Result<T, E>>): Result<T, E> (+3 overloads)

Evaluates the given generator to a Result returned or an Err yielded from it, whichever comes first.

This function is intended to emulate Rust's ? operator. See /tests/safeTry.test.ts for examples.

@parambody - What is evaluated. In body, yield* result works as Rust's result? expression.

@returnsThe first occurrence of either an yielded Err or a returned Result.

safeTry
,
function ok<T, E = never>(value: T): Ok<T, E> (+1 overload)
ok
} from "neverthrow"
declare function
function mayFail1(): ResultAsync<number, string>
mayFail1
():
class ResultAsync<T, E>
ResultAsync
<number, string>
declare function
function mayFail2(): ResultAsync<number, string>
mayFail2
():
class ResultAsync<T, E>
ResultAsync
<number, string>
function
function myFunc(): ResultAsync<number, string>
myFunc
():
class ResultAsync<T, E>
ResultAsync
<number, string> {
return
safeTry<number, string>(body: () => AsyncGenerator<Err<never, string>, Result<number, string>, any>): ResultAsync<number, string> (+3 overloads)

Evaluates the given generator to a Result returned or an Err yielded from it, whichever comes first.

This function is intended to emulate Rust's ? operator. See /tests/safeTry.test.ts for examples.

@parambody - What is evaluated. In body, yield* result and yield* resultAsync work as Rust's result? expression.

@returnsThe first occurrence of either an yielded Err or a returned Result.

safeTry
<number, string>(async function* () {
return
ok<number, never>(value: number): Ok<number, never> (+1 overload)
ok
(
(yield*
function mayFail1(): ResultAsync<number, string>
mayFail1
().
ResultAsync<number, string>.mapErr<string>(f: (e: string) => string | Promise<string>): ResultAsync<number, string>
mapErr
(
(
e: string
e
) => `aborted by an error from 1st function, ${
e: string
e
}`
)) +
(yield*
function mayFail2(): ResultAsync<number, string>
mayFail2
().
ResultAsync<number, string>.mapErr<string>(f: (e: string) => string | Promise<string>): ResultAsync<number, string>
mapErr
(
(
e: string
e
) => `aborted by an error from 2nd function, ${
e: string
e
}`
))
)
})
}

Note. With Effect.gen, you do not need to wrap the final value with Effect.succeed. The generator’s return value becomes the Success.