Skip to content
Effect Days 2026 Get your ticket
Docs menu / Effect vs neverthrow

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.

Synchronous API

ok

Example (Creating a success result)

import {
import ok
ok
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const result: any
result
=
import ok
ok
({
myData: string
myData
: "test" })
const result: any
result
.
any
isOk
() // true
const result: any
result
.
any
isErr
() // false
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
const
const result: any
result
=
import Either
Either
.
any
right
({
myData: string
myData
: "test" })
import Either
Either
.
any
isRight
(
const result: any
result
) // true
import Either
Either
.
any
isLeft
(
const result: any
result
) // false

err

Example (Creating a failure result)

import {
import err
err
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const result: any
result
=
import err
err
("Oh no")
const result: any
result
.
any
isOk
() // false
const result: any
result
.
any
isErr
() // true
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
const
const result: any
result
=
import Either
Either
.
any
left
("Oh no")
import Either
Either
.
any
isRight
(
const result: any
result
) // false
import Either
Either
.
any
isLeft
(
const result: any
result
) // true

map

Example (Transforming the success value)

import {
import Result
Result
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
declare function
function getLines(s: string): Result<Array<string>, Error>
getLines
(
s: string
s
: string):
import Result
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: any
newResult
=
const result: Result<string[], Error>
result
.
any
map
((arr) =>
arr: any
arr
.
any
map
(
function parseInt(string: string, radix?: number): number
parseInt
))
Error ts(7006) ― Parameter 'arr' implicitly has an 'any' type.
const newResult: any
newResult
.
any
isOk
() // true
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
declare function
function getLines(s: string): Either.Either<Array<string>, Error>
getLines
(
s: string
s
: string):
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<
interface Array<T>
Array
<string>,
interface Error
Error
>
const
const result: Either.Either<string[], Error>
result
=
function getLines(s: string): Either.Either<Array<string>, Error>
getLines
("1\n2\n3\n4\n")
// this Either now has a Array<number> inside it
const
const newResult: any
newResult
=
const result: Either.Either<string[], Error>
result
.
any
pipe
(
import Either
Either
.
any
map
((arr) =>
arr: any
arr
.
any
map
(
function parseInt(string: string, radix?: number): number
parseInt
)))
Error ts(7006) ― Parameter 'arr' implicitly has an 'any' type.
import Either
Either
.
any
isRight
(
const newResult: any
newResult
) // true

mapErr

Example (Transforming the error value)

import {
import Result
Result
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
declare function
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string,
):
import Result
Result
<
type Record<K extends keyof any, T> = { [P in K]: 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: any
newResult
=
const result: Result<Record<string, string>, string>
result
.
any
mapErr
((err) => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
(
err: any
err
))
Error ts(7006) ― Parameter 'err' implicitly has an 'any' type.
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
declare function
function parseHeaders(raw: string): Either.Either<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string,
):
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<
type Record<K extends keyof any, T> = { [P in K]: T; }
Record
<string, string>, string>
const
const rawHeaders: "nonsensical gibberish and badly formatted stuff"
rawHeaders
= "nonsensical gibberish and badly formatted stuff"
const
const result: Either.Either<Record<string, string>, string>
result
=
function parseHeaders(raw: string): Either.Either<Record<string, string>, string>
parseHeaders
(
const rawHeaders: "nonsensical gibberish and badly formatted stuff"
rawHeaders
)
// const newResult: Either<Record<string, string>, Error>
const
const newResult: any
newResult
=
const result: Either.Either<Record<string, string>, string>
result
.
any
pipe
(
import Either
Either
.
any
mapLeft
((err) => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
(
err: any
err
)))
Error ts(7006) ― Parameter 'err' implicitly has an 'any' type.

unwrapOr

Example (Providing a default value)

import {
import err
err
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const result: any
result
=
import err
err
("Oh no")
const
const multiply: (value: number) => number
multiply
= (
value: number
value
: number): number =>
value: number
value
* 2
const
const unwrapped: any
unwrapped
=
const result: any
result
.
any
map
(
const multiply: (value: number) => number
multiply
).
any
unwrapOr
(10)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
const
const result: any
result
=
import Either
Either
.
any
left
("Oh no")
const
const multiply: (value: number) => number
multiply
= (
value: number
value
: number): number =>
value: number
value
* 2
const
const unwrapped: any
unwrapped
=
const result: any
result
.
any
pipe
(
import Either
Either
.
any
map
(
const multiply: (value: number) => number
multiply
),
import Either
Either
.
any
getOrElse
(() => 10),
)

andThen

Example (Chaining computations that may fail)

import {
import ok
ok
,
import Result
Result
,
import err
err
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const sqrt: (n: number) => Result<number, string>
sqrt
= (
n: number
n
: number):
import Result
Result
<number, string> =>
n: number
n
> 0 ?
import ok
ok
(
var Math: Math
Math
.
Math.sqrt(x: number): number
sqrt
(
n: number
n
)) :
import err
err
("n must be positive")
import ok
ok
(16).
any
andThen
(
const sqrt: (n: number) => Result<number, string>
sqrt
).
any
andThen
(
const sqrt: (n: number) => Result<number, string>
sqrt
)
// Ok(2)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
const
const sqrt: (n: number) => Either.Either<number, string>
sqrt
= (
n: number
n
: number):
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string> =>
n: number
n
> 0 ?
import Either
Either
.
any
right
(
var Math: Math
Math
.
Math.sqrt(x: number): number
sqrt
(
n: number
n
)) :
import Either
Either
.
any
left
("n must be positive")
import Either
Either
.
any
right
(16).
any
pipe
(
import Either
Either
.
any
andThen
(
const sqrt: (n: number) => Either.Either<number, string>
sqrt
),
import Either
Either
.
any
andThen
(
const sqrt: (n: number) => Either.Either<number, string>
sqrt
))
// Right(2)

asyncAndThen

Example (Chaining asynchronous computations that may fail)

import {
import ok
ok
,
import okAsync
okAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
// const result: ResultAsync<number, never>
const
const result: any
result
=
import ok
ok
(1).
any
asyncAndThen
((n) =>
import okAsync
okAsync
(
n: any
n
+ 1))
Error ts(7006) ― Parameter 'n' implicitly has an 'any' type.
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
import * as
import Effect
Effect
from "effect/Effect"
// const result: Effect<number, never, never>
const
const result: any
result
=
import Either
Either
.
any
right
(1).
any
pipe
(
import Effect
Effect
.
const andThen: <unknown, any, never, never>(f: (a: unknown) => Effect.Effect<any, never, never>) => <E, R>(self: Effect.Effect<unknown, E, R>) => Effect.Effect<any, E, R> (+3 overloads)
andThen
((
n: unknown
n
) =>
import Effect
Effect
.
const succeed: <any>(value: any) => Effect.Effect<any, never, never>
succeed
(n + 1)),
Error ts(18046) ― 'n' is of type 'unknown'.
)

orElse

Example (Providing an alternative on failure)

import {
import Result
Result
,
import err
err
,
import ok
ok
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
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
:
import Result
Result
<string,
enum DatabaseError
DatabaseError
> =
import err
err
(
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
)
const
const updatedQueryResult: any
updatedQueryResult
=
const dbQueryResult: Result<string, DatabaseError>
dbQueryResult
.
any
orElse
((dbError) =>
Error ts(7006) ― Parameter 'dbError' implicitly has an 'any' type.
dbError: any
dbError
===
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
?
import ok
ok
("User does not exist") :
import err
err
(500),
)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
enum
enum DatabaseError
DatabaseError
{
function (enum member) DatabaseError.PoolExhausted = "PoolExhausted"
PoolExhausted
= "PoolExhausted",
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
= "NotFound",
}
const
const dbQueryResult: Either.Either<string, DatabaseError>
dbQueryResult
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<string,
enum DatabaseError
DatabaseError
> =
import Either
Either
.
any
left
(
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
,
)
const
const updatedQueryResult: any
updatedQueryResult
=
const dbQueryResult: Either.Either<string, DatabaseError>
dbQueryResult
.
any
pipe
(
import Either
Either
.
any
orElse
((dbError) =>
Error ts(7006) ― Parameter 'dbError' implicitly has an 'any' type.
dbError: any
dbError
===
enum DatabaseError
DatabaseError
.
function (enum member) DatabaseError.NotFound = "NotFound"
NotFound
?
import Either
Either
.
any
right
("User does not exist")
:
import Either
Either
.
any
left
(500),
),
)

match

Example (Pattern matching on success or failure)

import {
import Result
Result
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
declare const
const myResult: Result<number, string>
myResult
:
import Result
Result
<number, string>
const myResult: Result<number, string>
myResult
.
any
match
(
(value) => `The value is ${
value: any
value
}`,
Error ts(7006) ― Parameter 'value' implicitly has an 'any' type.
(error) => `The error is ${
error: any
error
}`,
Error ts(7006) ― Parameter 'error' implicitly has an 'any' type.
)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
declare const
const myResult: Either.Either<number, string>
myResult
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string>
const myResult: Either.Either<number, string>
myResult
.
any
pipe
(
import Either
Either
.
any
match
({
onLeft: (error: any) => string
onLeft
: (error) => `The error is ${
error: any
error
}`,
Error ts(7006) ― Parameter 'error' implicitly has an 'any' type.
onRight: (value: any) => string
onRight
: (value) => `The value is ${
value: any
value
}`,
Error ts(7006) ― Parameter 'value' implicitly has an 'any' type.
}),
)

asyncMap

Example (Parsing headers and looking up a user)

import {
import Result
Result
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string,
):
import Result
Result
<
type Record<K extends keyof any, T> = { [P in K]: T; }
Record
<string, string>, string>
declare function
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(
authorization: string
authorization
: string,
):
interface Promise<T>
Promise
<
interface User
User
| undefined>
const
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
= "Authorization: Bearer 1234567890"
// const asyncResult: ResultAsync<User | undefined, string>
const
const asyncResult: any
asyncResult
=
function parseHeaders(raw: string): Result<Record<string, string>, string>
parseHeaders
(
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
)
.
any
map
((kvMap) =>
kvMap: any
kvMap
["Authorization"])
Error ts(7006) ― Parameter 'kvMap' implicitly has an 'any' type.
.
any
asyncMap
((authorization) =>
Error ts(7006) ― Parameter 'authorization' implicitly has an 'any' type.
authorization: any
authorization
===
var undefined
undefined
?
var Promise: PromiseConstructor
Promise
.
PromiseConstructor.resolve<undefined>(value: undefined): Promise<undefined> (+2 overloads)
resolve
(
var undefined
undefined
)
:
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(
authorization: any
authorization
),
)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
import * as
import Effect
Effect
from "effect/Effect"
interface
interface User
User
{}
declare function
function parseHeaders(raw: string): Either.Either<Record<string, string>, string>
parseHeaders
(
raw: string
raw
: string,
):
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<
type Record<K extends keyof any, T> = { [P in K]: T; }
Record
<string, string>, string>
declare function
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(
authorization: string
authorization
: string,
):
interface Promise<T>
Promise
<
interface User
User
| undefined>
const
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
= "Authorization: Bearer 1234567890"
// const asyncResult: Effect<User | undefined, string | UnknownException>
const
const asyncResult: any
asyncResult
=
function parseHeaders(raw: string): Either.Either<Record<string, string>, string>
parseHeaders
(
const rawHeader: "Authorization: Bearer 1234567890"
rawHeader
).
any
pipe
(
import Either
Either
.
any
map
((kvMap) =>
kvMap: any
kvMap
["Authorization"]),
Error ts(7006) ― Parameter 'kvMap' implicitly has an 'any' type.
import Effect
Effect
.andThen((
authorization: unknown
authorization
) =>
Error ts(2769) ― No overload matches this call. Overload 1 of 4, '(f: (a: unknown) => Effect<unknown, unknown, unknown>): <E, R>(self: Effect<unknown, E, R>) => Effect<unknown, unknown, unknown>', gave the following error. Type 'Promise<User | undefined>' is missing the following properties from type 'Effect<unknown, unknown, unknown>': [TypeId], [Symbol.iterator], pipe, toJSON, [NodeInspectSymbol] Overload 2 of 4, '(f: Effect<unknown, unknown, unknown>): <A, E, R>(self: Effect<A, E, R>) => Effect<unknown, unknown, unknown>', gave the following error. Argument of type '(authorization: unknown) => Promise<User | undefined>' is not assignable to parameter of type 'Effect<unknown, unknown, unknown>'.
authorization: unknown
authorization
===
var undefined
undefined
?
var Promise: PromiseConstructor
Promise
.
PromiseConstructor.resolve<undefined>(value: undefined): Promise<undefined> (+2 overloads)
resolve
(
var undefined
undefined
)
:
function findUserInDatabase(authorization: string): Promise<User | undefined>
findUserInDatabase
(authorization),
Error ts(2345) ― Argument of type '{} | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
),
)

Note. In neverthrow, asyncMap works with Promises directly. In Effect, passing a Promise to combinators like Effect.andThen automatically lifts it into an Effect. If the Promise rejects, the rejection is turned into an UnknownException, which is why the error type is widened to string | UnknownException.

combine

Example (Combining multiple results)

import {
import Result
Result
,
import ok
ok
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const results: Result<number, string>[]
results
:
import Result
Result
<number, string>[] = [
import ok
ok
(1),
import ok
ok
(2)]
// const combined: Result<number[], string>
const
const combined: any
combined
=
import Result
Result
.
any
combine
(
const results: Result<number, string>[]
results
)
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
const
const results: Either.Either<number, string>[]
results
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string>[] = [
import Either
Either
.
any
right
(1),
import Either
Either
.
any
right
(2),
]
// const combined: Either<number[], string>
const
const combined: any
combined
=
import Either
Either
.
any
all
(
const results: Either.Either<number, string>[]
results
)

combineWithAllErrors

Example (Collecting all errors and successes)

import {
import Result
Result
,
import ok
ok
,
import err
err
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const results: Result<number, string>[]
results
:
import Result
Result
<number, string>[] = [
import ok
ok
(123),
import err
err
("boooom!"),
import ok
ok
(456),
import err
err
("ahhhhh!"),
]
const
const result: any
result
=
import Result
Result
.
any
combineWithAllErrors
(
const results: Result<number, string>[]
results
)
// result is Err(['boooom!', 'ahhhhh!'])
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
import * as
import Array
Array
from "effect/Array"
const
const results: Either.Either<number, string>[]
results
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string>[] = [
import Either
Either
.
any
right
(123),
import Either
Either
.
any
left
("boooom!"),
import Either
Either
.
any
right
(456),
import Either
Either
.
any
left
("ahhhhh!"),
]
const
const errors: any
errors
=
import Array
Array
.getLefts(
const results: Either.Either<number, string>[]
results
)
Error ts(2339) ― Property 'getLefts' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Array")'.
// errors is ['boooom!', 'ahhhhh!']
const
const successes: any
successes
=
import Array
Array
.getRights(
const results: Either.Either<number, string>[]
results
)
Error ts(2339) ― Property 'getRights' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Array")'.
// successes is [123, 456]

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.

Asynchronous API

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.

okAsync

Example (Creating a successful async result)

import {
import okAsync
okAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const myResultAsync: any
myResultAsync
=
import okAsync
okAsync
({
myData: string
myData
: "test" })
const
const result: any
result
= await
const myResultAsync: any
myResultAsync
const result: any
result
.
any
isOk
() // true
const result: any
result
.
any
isErr
() // false
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
import * as
import Effect
Effect
from "effect/Effect"
const
const myResultAsync: Effect.Effect<{
myData: string;
}, never, never>
myResultAsync
=
import Effect
Effect
.
const succeed: <{
myData: string;
}>(value: {
myData: string;
}) => Effect.Effect<{
myData: string;
}, never, never>
succeed
({
myData: string
myData
: "test" })
const
const result: unknown
result
= await
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const myResultAsync: Effect.Effect<{
myData: string;
}, never, never>
myResultAsync
))
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
import Either
Either
.
any
isRight
(
const result: unknown
result
) // true
import Either
Either
.
any
isLeft
(
const result: unknown
result
) // false

errAsync

Example (Creating a failed async result)

import {
import errAsync
errAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const myResultAsync: any
myResultAsync
=
import errAsync
errAsync
("Oh no")
const
const myResult: any
myResult
= await
const myResultAsync: any
myResultAsync
const myResult: any
myResult
.
any
isOk
() // false
const myResult: any
myResult
.
any
isErr
() // true
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
import * as
import Effect
Effect
from "effect/Effect"
const
const myResultAsync: Effect.Effect<never, string, never>
myResultAsync
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>
fail
("Oh no")
const
const result: unknown
result
= await
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const myResultAsync: Effect.Effect<never, string, never>
myResultAsync
))
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
import Either
Either
.
any
isRight
(
const result: unknown
result
) // false
import Either
Either
.
any
isLeft
(
const result: unknown
result
) // true

fromThrowable

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

import {
import ResultAsync
ResultAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function insertIntoDb(user: User): Promise<User>
insertIntoDb
(
user: User
user
:
interface User
User
):
interface Promise<T>
Promise
<
interface User
User
>
// (user: User) => ResultAsync<User, Error>
const
const insertUser: any
insertUser
=
import ResultAsync
ResultAsync
.
any
fromThrowable
(
function insertIntoDb(user: User): Promise<User>
insertIntoDb
,
() => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
("Database error"),
)
import * as
import Effect
Effect
from "effect/Effect"
interface
interface User
User
{}
declare function
function insertIntoDb(user: User): Promise<User>
insertIntoDb
(
user: User
user
:
interface User
User
):
interface Promise<T>
Promise
<
interface User
User
>
// (user: User) => Effect<User, Error>
const
const insertUser: (user: User) => Effect.Effect<User, Error, never>
insertUser
= (
user: User
user
:
interface User
User
) =>
import Effect
Effect
.
const tryPromise: <User, Error>(options: {
readonly try: (signal: AbortSignal) => PromiseLike<User>;
readonly catch: (error: unknown) => Error;
}) => Effect.Effect<User, Error, never> (+1 overload)
tryPromise
({
try: (signal: AbortSignal) => PromiseLike<User>
try
: () =>
function insertIntoDb(user: User): Promise<User>
insertIntoDb
(
user: User
user
),
catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
("Database error"),
})

map

Example (Transforming the success value)

import {
import Result
Result
,
import ResultAsync
ResultAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
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):
import ResultAsync
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: any
namesInCanada
=
const usersInCanada: ResultAsync<User[], Error>
usersInCanada
.
any
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[]
map
((
user: User
user
) =>
user: User
user
.
User.name: string
name
),
)
// We can extract the Result using .then() or await
const namesInCanada: any
namesInCanada
.
any
then
((
namesResult: Result<string[], Error>
namesResult
:
import Result
Result
<
interface Array<T>
Array
<string>,
interface Error
Error
>) => {
if (
namesResult: Result<string[], Error>
namesResult
.
any
isErr
()) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Couldn't get the users from the database",
namesResult: Result<string[], Error>
namesResult
.
any
error
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Users in Canada are named: " +
namesResult: Result<string[], Error>
namesResult
.
any
value
.
any
join
(","))
}
})
import * as
import Effect
Effect
from "effect/Effect"
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function findUsersIn(country: string): Effect.Effect<Array<User>, Error>
findUsersIn
(
country: string
country
: string):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
interface Array<T>
Array
<
interface User
User
>,
interface Error
Error
>
const
const usersInCanada: Effect.Effect<User[], Error, never>
usersInCanada
=
function findUsersIn(country: string): Effect.Effect<Array<User>, Error>
findUsersIn
("Canada")
const
const namesInCanada: Effect.Effect<string[], Error, never>
namesInCanada
=
const usersInCanada: Effect.Effect<User[], Error, never>
usersInCanada
.
Pipeable.pipe<Effect.Effect<User[], Error, never>, Effect.Effect<string[], Error, never>>(this: Effect.Effect<User[], Error, never>, ab: (_: Effect.Effect<User[], Error, never>) => Effect.Effect<string[], Error, never>): Effect.Effect<string[], Error, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const map: <User[], string[]>(f: (a: User[]) => string[]) => <E, R>(self: Effect.Effect<User[], E, R>) => Effect.Effect<string[], E, R> (+1 overload)
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[]
map
((
user: User
user
) =>
user: User
user
.
User.name: string
name
)),
)
// We can extract the Either using Effect.either
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const namesInCanada: Effect.Effect<string[], Error, never>
namesInCanada
)).
Promise<unknown>.then<void, never>(onfulfilled?: ((value: unknown) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
then
(
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
(
namesResult: Either.Either<string[], Error>
namesResult
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<
interface Array<T>
Array
<string>,
interface Error
Error
>) => {
if (
import Either
Either
.
any
isLeft
(
namesResult: Either.Either<string[], Error>
namesResult
)) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Couldn't get the users from the database",
namesResult: Either.Either<string[], Error>
namesResult
.
any
left
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Users in Canada are named: " +
namesResult: Either.Either<string[], Error>
namesResult
.
any
right
.
any
join
(","))
}
},
)

mapErr

Example (Transforming the error value)

import {
import Result
Result
,
import ResultAsync
ResultAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
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):
import ResultAsync
ResultAsync
<
interface Array<T>
Array
<
interface User
User
>,
interface Error
Error
>
const
const usersInCanada: any
usersInCanada
=
function findUsersIn(country: string): ResultAsync<Array<User>, Error>
findUsersIn
("Canada").
any
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: any
usersInCanada
.
any
then
((
usersResult: Result<User[], string>
usersResult
:
import Result
Result
<
interface Array<T>
Array
<
interface User
User
>, string>) => {
if (
usersResult: Result<User[], string>
usersResult
.
any
isErr
()) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Couldn't get the users from the database",
usersResult: Result<User[], string>
usersResult
.
any
error
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Users in Canada are: " +
usersResult: Result<User[], string>
usersResult
.
any
value
.
any
join
(","))
}
})
import * as
import Effect
Effect
from "effect/Effect"
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function findUsersIn(country: string): Effect.Effect<Array<User>, Error>
findUsersIn
(
country: string
country
: string):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
interface Array<T>
Array
<
interface User
User
>,
interface Error
Error
>
const
const usersInCanada: Effect.Effect<User[], "Unknown country" | "System error, please contact an administrator.", never>
usersInCanada
=
function findUsersIn(country: string): Effect.Effect<Array<User>, Error>
findUsersIn
("Canada").
Pipeable.pipe<Effect.Effect<User[], Error, never>, Effect.Effect<User[], "Unknown country" | "System error, please contact an administrator.", never>>(this: Effect.Effect<User[], Error, never>, ab: (_: Effect.Effect<User[], Error, never>) => Effect.Effect<User[], "Unknown country" | "System error, please contact an administrator.", never>): Effect.Effect<User[], "Unknown country" | "System error, please contact an administrator.", never> (+21 overloads)
pipe
(
import Effect
Effect
.
const mapError: <Error, "Unknown country" | "System error, please contact an administrator.">(f: (e: Error) => "Unknown country" | "System error, please contact an administrator.") => <A, R>(self: Effect.Effect<A, Error, R>) => Effect.Effect<A, "Unknown country" | "System error, please contact an administrator.", R> (+1 overload)
mapError
((
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."
}),
)
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const usersInCanada: Effect.Effect<User[], "Unknown country" | "System error, please contact an administrator.", never>
usersInCanada
)).
Promise<unknown>.then<void, never>(onfulfilled?: ((value: unknown) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
then
(
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
(
usersResult: Either.Either<User[], string>
usersResult
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<
interface Array<T>
Array
<
interface User
User
>, string>) => {
if (
import Either
Either
.
any
isLeft
(
usersResult: Either.Either<User[], string>
usersResult
)) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Couldn't get the users from the database",
usersResult: Either.Either<User[], string>
usersResult
.
any
left
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Users in Canada are: " +
usersResult: Either.Either<User[], string>
usersResult
.
any
right
.
any
join
(","))
}
},
)

unwrapOr

Example (Providing a default value when async fails)

import {
import errAsync
errAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const unwrapped: any
unwrapped
= await
import errAsync
errAsync
(0).
any
unwrapOr
(10)
// unwrapped = 10
import * as
import Effect
Effect
from "effect/Effect"
const
const unwrapped: number
unwrapped
= await
import Effect
Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: Effect.RunOptions | undefined) => Promise<number>
runPromise
(
import Effect
Effect
.
const fail: <number>(error: number) => Effect.Effect<never, number, never>
fail
(0).
Pipeable.pipe<Effect.Effect<never, number, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<never, number, never>, ab: (_: Effect.Effect<never, number, never>) => Effect.Effect<number, never, never>): Effect.Effect<number, never, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const orElseSucceed: <number>(evaluate: LazyArg<number>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number | A, never, R> (+1 overload)
orElseSucceed
(() => 10)),
)
// unwrapped = 10

andThen

Example (Chaining multiple async computations)

import {
import Result
Result
,
import ResultAsync
ResultAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
user: User
user
:
interface User
User
):
import ResultAsync
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): ResultAsync<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
import ResultAsync
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function sendNotification(user: User): ResultAsync<void, Error>
sendNotification
(
user: User
user
:
interface User
User
):
import ResultAsync
ResultAsync
<void,
interface Error
Error
>
const
const user: User
user
:
interface User
User
= {}
const
const resAsync: any
resAsync
=
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
const user: User
user
)
.
any
andThen
(
function insertUser(user: User): ResultAsync<User, Error>
insertUser
)
.
any
andThen
(
function sendNotification(user: User): ResultAsync<void, Error>
sendNotification
)
const resAsync: any
resAsync
.
any
then
((
res: Result<void, Error>
res
:
import Result
Result
<void,
interface Error
Error
>) => {
if (
res: Result<void, Error>
res
.
any
isErr
()) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Oops, at least one step failed",
res: Result<void, Error>
res
.
any
error
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
("User has been validated, inserted and notified successfully.")
}
})
import * as
import Effect
Effect
from "effect/Effect"
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function validateUser(user: User): Effect.Effect<User, Error>
validateUser
(
user: User
user
:
interface User
User
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): Effect.Effect<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
interface User
User
,
interface Error
Error
>
declare function
function sendNotification(user: User): Effect.Effect<void, Error>
sendNotification
(
user: User
user
:
interface User
User
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<void,
interface Error
Error
>
const
const user: User
user
:
interface User
User
= {}
const
const resAsync: Effect.Effect<void, Error, never>
resAsync
=
function validateUser(user: User): Effect.Effect<User, Error>
validateUser
(
const user: User
user
).
Pipeable.pipe<Effect.Effect<User, Error, never>, Effect.Effect<User, Error, never>, Effect.Effect<void, Error, never>>(this: Effect.Effect<User, Error, never>, ab: (_: Effect.Effect<User, Error, never>) => Effect.Effect<User, Error, never>, bc: (_: Effect.Effect<User, Error, never>) => Effect.Effect<void, Error, never>): Effect.Effect<void, Error, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const andThen: <User, User, Error, never>(f: (a: User) => Effect.Effect<User, Error, never>) => <E, R>(self: Effect.Effect<User, E, R>) => Effect.Effect<User, Error | E, R> (+3 overloads)
andThen
(
function insertUser(user: User): Effect.Effect<User, Error>
insertUser
),
import Effect
Effect
.
const andThen: <User, void, Error, never>(f: (a: User) => Effect.Effect<void, Error, never>) => <E, R>(self: Effect.Effect<User, E, R>) => Effect.Effect<void, Error | E, R> (+3 overloads)
andThen
(
function sendNotification(user: User): Effect.Effect<void, Error>
sendNotification
),
)
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const resAsync: Effect.Effect<void, Error, never>
resAsync
)).
Promise<unknown>.then<void, never>(onfulfilled?: ((value: unknown) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
then
(
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
(
res: Either.Either<void, Error>
res
:
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<void,
interface Error
Error
>) => {
if (
import Either
Either
.
any
isLeft
(
res: Either.Either<void, Error>
res
)) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("Oops, at least one step failed",
res: Either.Either<void, Error>
res
.
any
left
)
} else {
var console: Console
console
.
Console.log(...data: any[]): void
log
(
"User has been validated, inserted and notified successfully.",
)
}
},
)

orElse

Example (Fallback when an async operation fails)

import {
import ResultAsync
ResultAsync
,
import ok
ok
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function fetchUserData(id: string): ResultAsync<User, Error>
fetchUserData
(
id: string
id
: string):
import ResultAsync
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: any
userResult
=
function fetchUserData(id: string): ResultAsync<User, Error>
fetchUserData
(
const userId: "123"
userId
).
any
orElse
(() =>
import ok
ok
(
function getDefaultUser(): User
getDefaultUser
()))
const userResult: any
userResult
.
any
then
((result) => {
Error ts(7006) ― Parameter 'result' implicitly has an 'any' type.
if (
result: any
result
.
any
isOk
()) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("User data:",
result: any
result
.
any
value
)
}
})
import * as
import Effect
Effect
from "effect/Effect"
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
interface
interface User
User
{}
declare function
function fetchUserData(id: string): Effect.Effect<User, Error>
fetchUserData
(
id: string
id
: string):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
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: never
userResult
=
function fetchUserData(id: string): Effect.Effect<User, Error>
fetchUserData
(
const userId: "123"
userId
).
Pipeable.pipe<Effect.Effect<User, Error, never>, never>(this: Effect.Effect<User, Error, never>, ab: (_: Effect.Effect<User, Error, never>) => never): never (+21 overloads)
pipe
(
import Effect
Effect
.orElse(() =>
import Effect
Effect
.
const succeed: <User>(value: User) => Effect.Effect<User, never, never>
succeed
(
function getDefaultUser(): User
getDefaultUser
())),
Error ts(2339) ― Property 'orElse' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
)
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
const userResult: never
userResult
)).
Promise<unknown>.then<void, never>(onfulfilled?: ((value: unknown) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
then
((
result: unknown
result
) => {
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
if (
import Either
Either
.
any
isRight
(
result: unknown
result
)) {
var console: Console
console
.
Console.log(...data: any[]): void
log
("User data:", result.
any
right
)
Error ts(18046) ― 'result' is of type 'unknown'.
}
})

match

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

import {
import ResultAsync
ResultAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
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
):
import ResultAsync
ResultAsync
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): ResultAsync<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
import ResultAsync
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: any
resultMessage
= await
function validateUser(user: User): ResultAsync<User, Error>
validateUser
(
const user: User
user
)
.
any
andThen
(
function insertUser(user: User): ResultAsync<User, Error>
insertUser
)
.
any
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
}`,
)
import * as
import Effect
Effect
from "effect/Effect"
interface
interface User
User
{
readonly
User.name: string
name
: string
}
declare function
function validateUser(user: User): Effect.Effect<User, Error>
validateUser
(
user: User
user
:
interface User
User
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
interface User
User
,
interface Error
Error
>
declare function
function insertUser(user: User): Effect.Effect<User, Error>
insertUser
(
user: User
user
:
interface User
User
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<
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
import Effect
Effect
.
const runPromise: <string, never>(effect: Effect.Effect<string, never, never>, options?: Effect.RunOptions | undefined) => Promise<string>
runPromise
(
function validateUser(user: User): Effect.Effect<User, Error>
validateUser
(
const user: User
user
).
Pipeable.pipe<Effect.Effect<User, Error, never>, Effect.Effect<User, Error, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<User, Error, never>, ab: (_: Effect.Effect<User, Error, never>) => Effect.Effect<User, Error, never>, bc: (_: Effect.Effect<User, Error, never>) => Effect.Effect<string, never, never>): Effect.Effect<string, never, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const andThen: <User, User, Error, never>(f: (a: User) => Effect.Effect<User, Error, never>) => <E, R>(self: Effect.Effect<User, E, R>) => Effect.Effect<User, Error | E, R> (+3 overloads)
andThen
(
function insertUser(user: User): Effect.Effect<User, Error>
insertUser
),
import Effect
Effect
.
const match: <Error, string, User, string>(options: {
readonly onFailure: (error: Error) => string;
readonly onSuccess: (value: User) => string;
}) => <R>(self: Effect.Effect<User, Error, R>) => Effect.Effect<string, never, R> (+1 overload)
match
({
onSuccess: (value: User) => string
onSuccess
: (
user: User
user
) => `User ${
user: User
user
.
User.name: string
name
} has been successfully created`,
onFailure: (error: Error) => string
onFailure
: (
error: Error
error
) =>
`User could not be created because ${
error: Error
error
.
Error.message: string
message
}`,
}),
),
)

combine

Example (Combining multiple async results)

import {
import ResultAsync
ResultAsync
,
import okAsync
okAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const resultList: ResultAsync<number, string>[]
resultList
:
import ResultAsync
ResultAsync
<number, string>[] = [
import okAsync
okAsync
(1),
import okAsync
okAsync
(2)]
// const combinedList: ResultAsync<number[], string>
const
const combinedList: any
combinedList
=
import ResultAsync
ResultAsync
.
any
combine
(
const resultList: ResultAsync<number, string>[]
resultList
)
import * as
import Effect
Effect
from "effect/Effect"
const
const resultList: Effect.Effect<number, string, never>[]
resultList
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<number, string>[] = [
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(1),
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(2),
]
// const combinedList: Effect<number[], string>
const
const combinedList: Effect.Effect<number[], string, never>
combinedList
=
import Effect
Effect
.
const all: <Effect.Effect<number, string, never>[], {
readonly concurrency?: Concurrency | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "result" | undefined;
}>(arg: Effect.Effect<number, string, never>[], options?: {
readonly concurrency?: Concurrency | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "result" | undefined;
} | undefined) => Effect.Effect<number[], string, never>
all
(
const resultList: Effect.Effect<number, string, never>[]
resultList
)

combineWithAllErrors

Example (Collecting all errors instead of failing fast)

import {
import ResultAsync
ResultAsync
,
import okAsync
okAsync
,
import errAsync
errAsync
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
const
const resultList: ResultAsync<number, string>[]
resultList
:
import ResultAsync
ResultAsync
<number, string>[] = [
import okAsync
okAsync
(123),
import errAsync
errAsync
("boooom!"),
import okAsync
okAsync
(456),
import errAsync
errAsync
("ahhhhh!"),
]
const
const result: any
result
= await
import ResultAsync
ResultAsync
.
any
combineWithAllErrors
(
const resultList: ResultAsync<number, string>[]
resultList
)
// result is Err(['boooom!', 'ahhhhh!'])
import {
import Effect
Effect
,
const identity: <A>(a: A) => A
identity
} from "effect"
const
const resultList: Effect.Effect<number, string, never>[]
resultList
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<number, string>[] = [
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(123),
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>
fail
("boooom!"),
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(456),
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>
fail
("ahhhhh!"),
]
const
const result: unknown
result
= await
import Effect
Effect
.
const runPromise: <unknown, unknown>(effect: Effect.Effect<unknown, unknown, never>, options?: Effect.RunOptions | undefined) => Promise<unknown>
runPromise
(
import Effect
Effect
.either(
import Effect
Effect
.validateAll(
const resultList: Effect.Effect<number, string, never>[]
resultList
,
const identity: <A>(a: A) => A
identity
)),
Error ts(2339) ― Property 'either' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'.
Error ts(2551) ― Property 'validateAll' does not exist on type 'typeof import("/home/runner/work/website/website/node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect")'. Did you mean 'validate'?
)
// result is left(['boooom!', 'ahhhhh!'])

Utilities

fromThrowable

Example (Safely wrapping a throwing function)

import {
import Result
Result
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
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: any
safeJsonParse
=
import Result
Result
.
any
fromThrowable
(
var JSON: JSON
JSON
.
JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
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: any
result
=
const safeJsonParse: any
safeJsonParse
("{")
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
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: (s: string) => any
safeJsonParse
= (
s: string
s
: string) =>
import Either
Either
.
any
try
({
try: () => any
try
: () =>
var JSON: JSON
JSON
.
JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
parse
(
s: string
s
),
catch: () => ParseError
catch
:
const toParseError: () => ParseError
toParseError
})
// the function can now be used safely,
// if the function throws, the result will be an Either
const
const result: any
result
=
const safeJsonParse: (s: string) => any
safeJsonParse
("{")

safeTry

Example (Using generators to simplify error handling)

import {
import Result
Result
,
import ok
ok
,
import safeTry
safeTry
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
declare function
function mayFail1(): Result<number, string>
mayFail1
():
import Result
Result
<number, string>
declare function
function mayFail2(): Result<number, string>
mayFail2
():
import Result
Result
<number, string>
function
function myFunc(): Result<number, string>
myFunc
():
import Result
Result
<number, string> {
return
import safeTry
safeTry
<number, string>(function* () {
return
import ok
ok
(
(yield*
function mayFail1(): Result<number, string>
mayFail1
().
any
mapErr
(
(e) => `aborted by an error from 1st function, ${
e: any
e
}`,
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
)) +
(yield*
function mayFail2(): Result<number, string>
mayFail2
().
any
mapErr
(
(e) => `aborted by an error from 2nd function, ${
e: any
e
}`,
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
)),
)
})
}
import * as
import Either
Either
from "effect/Either"
Error ts(2307) ― Cannot find module 'effect/Either' or its corresponding type declarations.
declare function
function mayFail1(): Either.Either<number, string>
mayFail1
():
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string>
declare function
function mayFail2(): Either.Either<number, string>
mayFail2
():
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string>
function
function myFunc(): Either.Either<number, string>
myFunc
():
import Either
Either
.
type Either.Either = /*unresolved*/ any
Either
<number, string> {
return
import Either
Either
.
any
gen
(function* () {
return (
(yield*
function mayFail1(): Either.Either<number, string>
mayFail1
().
any
pipe
(
import Either
Either
.
any
mapLeft
((e) => `aborted by an error from 1st function, ${
e: any
e
}`),
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
)) +
(yield*
function mayFail2(): Either.Either<number, string>
mayFail2
().
any
pipe
(
import Either
Either
.
any
mapLeft
((e) => `aborted by an error from 2nd function, ${
e: any
e
}`),
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
))
)
})
}

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 {
import ResultAsync
ResultAsync
,
import safeTry
safeTry
,
import ok
ok
} from "neverthrow"
Error ts(2307) ― Cannot find module 'neverthrow' or its corresponding type declarations.
declare function
function mayFail1(): ResultAsync<number, string>
mayFail1
():
import ResultAsync
ResultAsync
<number, string>
declare function
function mayFail2(): ResultAsync<number, string>
mayFail2
():
import ResultAsync
ResultAsync
<number, string>
function
function myFunc(): ResultAsync<number, string>
myFunc
():
import ResultAsync
ResultAsync
<number, string> {
return
import safeTry
safeTry
<number, string>(async function* () {
return
import ok
ok
(
(yield*
function mayFail1(): ResultAsync<number, string>
mayFail1
().
any
mapErr
(
(e) => `aborted by an error from 1st function, ${
e: any
e
}`,
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
)) +
(yield*
function mayFail2(): ResultAsync<number, string>
mayFail2
().
any
mapErr
(
(e) => `aborted by an error from 2nd function, ${
e: any
e
}`,
Error ts(7006) ― Parameter 'e' implicitly has an 'any' type.
)),
)
})
}
import {
import Effect
Effect
} from "effect"
declare function
function mayFail1(): Effect.Effect<number, string>
mayFail1
():
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<number, string>
declare function
function mayFail2(): Effect.Effect<number, string>
mayFail2
():
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<number, string>
function
function myFunc(): Effect.Effect<number, string>
myFunc
():
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never>
Effect
<number, string> {
return
import Effect
Effect
.
const gen: <Effect.Effect<number, string, never>, number>(f: () => Generator<Effect.Effect<number, string, never>, number, never>) => Effect.Effect<number, string, never> (+1 overload)
gen
(function* () {
return (
(yield*
function mayFail1(): Effect.Effect<number, string>
mayFail1
().
Pipeable.pipe<Effect.Effect<number, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<number, string, never>, ab: (_: Effect.Effect<number, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<number, string, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const mapError: <string, string>(f: (e: string) => string) => <A, R>(self: Effect.Effect<A, string, R>) => Effect.Effect<A, string, R> (+1 overload)
mapError
((
e: string
e
) => `aborted by an error from 1st function, ${
e: string
e
}`),
)) +
(yield*
function mayFail2(): Effect.Effect<number, string>
mayFail2
().
Pipeable.pipe<Effect.Effect<number, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<number, string, never>, ab: (_: Effect.Effect<number, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<number, string, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const mapError: <string, string>(f: (e: string) => string) => <A, R>(self: Effect.Effect<A, string, R>) => Effect.Effect<A, string, R> (+1 overload)
mapError
((
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.