### JavaScript Array Map Example Source: https://github.com/supermacro/neverthrow/wiki/I-thought-.map-was-for-arrays?? Demonstrates the usage of the `Array.prototype.map` method in JavaScript, which transforms each element of an array using a provided callback function and returns a new array with the transformed elements. This serves as a familiar example of mapping over a container. ```javascript [1, 2, 3].map(num => `number is: ${num}`) ``` -------------------------------- ### Compare Error Handling: Callbacks, Async/Await, and Neverthrow Source: https://github.com/supermacro/neverthrow/wiki/Working-with-ResultAsync This example contrasts three methods of handling asynchronous operations and their errors: traditional Promise `.then/.catch` with callbacks, `async/await` with `try/catch`, and Neverthrow's `ResultAsync` with `fromPromise` and `match`. It illustrates how Neverthrow provides a more declarative and typesafe way to manage success and failure. ```typescript const callbackUser = () => { const userPromise = prisma.user.findUnique(...) userPromise .then(user => console.log("Found my user", user)) .catch(err => console.error("Error while reading user", err)) } ``` ```typescript const asyncAwaiter = async () => { try { const user = await prisma.user.findUnique(...) console.log("Found my user", user) } catch (err) { console.error("Error while reading user", err) } } ``` ```typescript const neverthrower = () => { const userPromise = prisma.user.findUnique(...) const result = fromPromise(userPromise, originalError => ({originalError, message: "Error while reading user"})) result.match( user => console.log("Found my user", user), err => console.log(err.message, err.originalError) ) } ``` -------------------------------- ### Asynchronously Fetch Data with TypeScript and neverthrow Source: https://github.com/supermacro/neverthrow/wiki/Error-Handling-Best-Practices This example demonstrates how to wrap an asynchronous operation (like an HTTP request using axios) into a ResultAsync type. It uses ResultAsync.fromPromise to convert a Promise-based API into a monadic Result, handling potential errors during the asynchronous call and mapping them to a specific HTTPError type. ```typescript import { ResultAsync } from 'neverthrow' const getBookById = (id: string): ResultAsync => ResultAsync.fromPromise( axios.get(`${BOOK_SERVICE_BASE_URL}/books/${id}`), (error: unknown) => { return intoHttpError(error) } ) ``` -------------------------------- ### Compare Result Instances Directly Source: https://github.com/supermacro/neverthrow/blob/master/README.md Shows how to assert expectations by comparing Result objects directly using the ok constructor, avoiding the need for manual unwrapping. ```typescript import { ok } from 'neverthrow' expect(callSomeFunctionThatReturnsAResult("with", "some", "args")).toEqual(ok(someExpectation)); ``` -------------------------------- ### TypeScript: Using the 'neverthrow' Package for Result Type Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Demonstrates how to import and use the 'ok', 'err', and 'Result' types from the 'neverthrow' package to handle asynchronous operations with type-safe error management. ```typescript import { ok, err, Result } from 'neverthrow' // we'll keep this simple type ResponseBody = {} interface ResponseData { statusCode: number responseBody?: ResponseBody } const isUrl = (url: string): boolean => { // Dummy implementation for example return url.startsWith('http'); } const makeHttpRequest = async ( url: string ): Promise> => { if (!isUrl(url)) { return err(new Error( 'Invalid string passed into `makeHttpRequest`. Expected a valid URL.' )) } // ... // other business logic here // ... return ok({ statusCode: 200 }) // Ok(ResponseData) } ``` -------------------------------- ### Type Guarding Results with Neverthrow in TypeScript Source: https://github.com/supermacro/neverthrow/wiki/Accessing-The-Value-Inside-A-Result This snippet demonstrates how to use the `.isOk()` and `.isErr()` type guards provided by Neverthrow. These methods allow the TypeScript compiler to infer the type of the contained value (either `value` for Ok or `error` for Err), preventing runtime errors and improving code clarity. It requires the 'neverthrow' library to be installed. ```typescript import { ok, err } from 'neverthrow' const example1 = ok(123) const example2 = err('abc') if (example1.isOk()) { // you now have access to example1.value doSomethingUseful(example1.value) } else { // you now have access to example1.error handleError(example1.error) } if (example2.isErr()) { // you now have access to example2.error handleError(example2.error) } else { // you now have access to example2.value doSomethingUseful(example2.value) } ``` -------------------------------- ### Simplifying types with Type Aliases Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Demonstrates how to use TypeScript type aliases to make verbose Result types more readable and expressive. ```typescript type DbResult = Result // Example of complex type aliasing handler: (req: Request, res: SessionManager) => DecodeResult>> ``` -------------------------------- ### Create Ok Result with neverthrow Source: https://context7.com/supermacro/neverthrow/llms.txt Demonstrates how to create an 'Ok' variant of the Result type using the `ok` function. This represents a successful operation and can hold a value of any type. It's the primary way to initiate a success chain in neverthrow. ```typescript import { ok, err, Result } from 'neverthrow' // Create a simple Ok result const successResult = ok(42) console.log(successResult.isOk()) // true console.log(successResult.isErr()) // false // Type-safe result with explicit error type const typedResult: Result = ok(100) // Access the value after type narrowing if (typedResult.isOk()) { console.log(typedResult.value) // 100 } // Ok with complex data const userResult = ok({ id: 1, name: 'Alice', email: 'alice@example.com' }) console.log(userResult._unsafeUnwrap()) // { id: 1, name: 'Alice', email: 'alice@example.com' } ``` -------------------------------- ### Synchronous safeTry with Generator Functions Source: https://github.com/supermacro/neverthrow/blob/master/README.md Demonstrates the basic usage of safeTry with synchronous generator functions. It shows how `yield*` unwraps `Ok` values or returns early on `Err`, reducing the need for manual error checks. ```typescript declare function mayFail1(): Result; declare function mayFail2(): Result; function myFunc(): Result { return safeTry(function*() { return ok( (yield* mayFail1() .mapErr(e => `aborted by an error from 1st function, ${e}`)) + (yield* mayFail2() .mapErr(e => `aborted by an error from 2nd function, ${e}`)) ) }) } ``` -------------------------------- ### Initialize neverthrow imports Source: https://github.com/supermacro/neverthrow/blob/master/README.md Import core classes and utility functions from the neverthrow package to handle Result and ResultAsync types. ```typescript import { ok, Ok, err, Err, Result, okAsync, errAsync, ResultAsync, fromAsyncThrowable, fromThrowable, fromPromise, fromSafePromise, safeTry } from 'neverthrow'; ``` -------------------------------- ### ResultAsync.combine Source: https://context7.com/supermacro/neverthrow/llms.txt Combines an array of ResultAsync instances into a single ResultAsync, executing them concurrently and short-circuiting on the first error. ```APIDOC ## ResultAsync.combine ### Description Combines an array of ResultAsyncs into a single ResultAsync containing an array of values. Executes all promises concurrently and short-circuits on first error. ### Method Static Method ### Endpoint ResultAsync.combine(results) ### Parameters #### Request Body - **results** (Array) - Required - An array of ResultAsync instances to be executed in parallel. ### Request Example ResultAsync.combine([okAsync(1), okAsync(2)]) ### Response #### Success Response (200) - **ResultAsync, E>** (object) - A ResultAsync containing the array of successful values. ``` -------------------------------- ### Synchronous Result Handling with neverthrow Source: https://github.com/supermacro/neverthrow/wiki/Basic-Usage-Examples Demonstrates creating Ok and Err instances and using type guards to safely access values or errors. This approach ensures type safety when branching logic based on operation success. ```typescript import { ok, err } from 'neverthrow' const yesss = ok(someAesomeValue) const mappedYes = yesss.map(doingSuperUsefulStuff) if (mappedYes.isOk()) { doStuffWith(mappedYes.value) } else { doStuffWith(mappedYes.error) } ``` -------------------------------- ### Chain Asynchronous Operations with ResultAsync.andThen Source: https://context7.com/supermacro/neverthrow/llms.txt Demonstrates how to chain multiple Result or ResultAsync operations. The chain short-circuits automatically if any step returns an error. ```typescript import { ok, err, okAsync, errAsync, ResultAsync, Result } from 'neverthrow' const result = okAsync(5) .andThen(n => n > 0 ? okAsync(n * 2) : errAsync('Must be positive')) console.log((await result)._unsafeUnwrap()) // 10 async function registerUser(data: RegistrationData): ResultAsync { return validateRegistration(data) .andThen(valid => createUser(valid)) .andThen(user => sendWelcomeEmail(user).map(() => user)) .andThen(user => createDefaultSettings(user.id).map(() => user)) } ``` -------------------------------- ### Using Type Guards with Neverthrow Results Source: https://github.com/supermacro/neverthrow/wiki/Accessing-The-Value-Inside-A-Result Demonstrates how to use `.isOk()` and `.isErr()` to narrow down the type of a Neverthrow Result and safely access its contents. ```APIDOC ## Using Type Guards with Neverthrow Results ### Description This example shows how to use the `isOk` and `isErr` methods provided by Neverthrow to perform type guards. By checking the result of these methods, you can inform the TypeScript compiler whether you are dealing with an `Ok` or `Err` instance, allowing safe access to the `value` or `error` properties respectively. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```typescript import { ok, err } from 'neverthrow' const example1 = ok(123) const example2 = err('abc') if (example1.isOk()) { // TypeScript knows example1 is an Ok instance here // and example1.value is of type number doSomethingUseful(example1.value) } else { // TypeScript knows example1 is an Err instance here // and example1.error is of type string handleError(example1.error) } if (example2.isErr()) { // TypeScript knows example2 is an Err instance here // and example2.error is of type string handleError(example2.error) } else { // TypeScript knows example2 is an Ok instance here // and example2.value is of type number doSomethingUseful(example2.value) } function doSomethingUseful(value: number): void { console.log(`Success: ${value}`) } function handleError(error: string): void { console.error(`Error: ${error}`) } ``` ### Response #### Success Response (200) N/A (Illustrative Example) #### Response Example N/A (Illustrative Example) ``` -------------------------------- ### Create Ok ResultAsync (TypeScript) Source: https://github.com/supermacro/neverthrow/blob/master/README.md Constructs an `Ok` variant of `ResultAsync`. This is used to wrap a successful asynchronous operation's result. ```typescript import { okAsync } from 'neverthrow' const myResultAsync = okAsync({ myData: 'test' }) // instance of `ResultAsync` const myResult = await myResultAsync // instance of `Ok` myResult.isOk() // true myResult.isErr() // false ``` -------------------------------- ### Result.andThrough Source: https://github.com/supermacro/neverthrow/blob/master/README.md Chains a Result-returning function to the success path, propagating errors if the callback fails. ```APIDOC ## Result.andThrough ### Description Similar to andTee, but if the callback returns an Err, that error is propagated into the resulting Result type. ### Method Method Call ### Parameters - **callback** (function) - Required - A function that takes the success value (T) and returns a Result. ### Request Example ```typescript const res = parseUserInput(input).andThrough(validateUser); ``` ### Response - **Result** - The original Result or the new error if the callback fails. ``` -------------------------------- ### okAsync Source: https://context7.com/supermacro/neverthrow/llms.txt Creates a ResultAsync containing an Ok value for async operations. ```APIDOC ## FUNCTION okAsync ### Description Creates a `ResultAsync` containing an `Ok` value. This is the async counterpart to `ok`, useful when working with async operations that are guaranteed to succeed. ### Method Function ### Parameters #### Arguments - **value** (T) - Required - The success value to wrap. ### Response - **ResultAsync** - An async result object. ``` -------------------------------- ### ResultAsync Constructors Source: https://github.com/supermacro/neverthrow/blob/master/README.md Utility methods to construct ResultAsync instances from values or errors. ```APIDOC ## okAsync / errAsync ### Description Constructs an Ok or Err variant of ResultAsync. ### Methods - **okAsync(value: T)**: Returns a ResultAsync that resolves to an Ok variant. - **errAsync(error: E)**: Returns a ResultAsync that resolves to an Err variant. ### Example ```typescript import { okAsync, errAsync } from 'neverthrow'; const success = okAsync({ data: 'test' }); const failure = errAsync('error message'); ``` ``` -------------------------------- ### Construct Result variants Source: https://github.com/supermacro/neverthrow/blob/master/README.md Use the ok and err convenience functions to create instances of the Result type. ```typescript import { ok, err } from 'neverthrow'; const myOk = ok({ myData: 'test' }); const myErr = err('Oh noooo'); ``` -------------------------------- ### Create ResultAsync from a safe promise Source: https://github.com/supermacro/neverthrow/blob/master/README.md Demonstrates how to wrap a promise in a ResultAsync object. Note that this method does not handle promise rejections, so it should be used when the promise is guaranteed not to throw. ```typescript export const slowDown = (ms: number) => (value: T) => ResultAsync.fromSafePromise( new Promise((resolve) => { setTimeout(() => { resolve(value) }, ms) }) ) ``` -------------------------------- ### Transforming Result values with map Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Demonstrates how to use the .map method on a Result object to process successful values returned from an asynchronous operation. ```typescript import { makeHttpRequest } from './http-api.ts' const run = async () => { const result = await makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1') result.map(responseData => { console.log(responseData) }) } run() ``` -------------------------------- ### Result.match: Handle Ok and Err cases Source: https://github.com/supermacro/neverthrow/blob/master/README.md The match method allows you to handle both the Ok and Err variants of a Result by providing two callback functions. It executes the appropriate callback based on the Result's state and returns a value of a common type, ensuring that both outcomes are addressed. ```typescript // Example with side effects computationThatMightFail().match(console.log, console.error) // Example returning values const answer = computationThatMightFail().match( (str) => str.toUpperCase(), (err) => `Error: ${err}` ) // Equivalent to map and unwrapOr if error callback is ignored const answerEquivalent = computationThatMightFail().match( (str) => str.toUpperCase(), () => 'ComputationError' ) ``` -------------------------------- ### Result.combine Source: https://github.com/supermacro/neverthrow/blob/master/README.md Combines a list of Results into a single Result, succeeding only if all Results in the list are Ok. ```APIDOC ## Result.combine (static class method) ### Description Combine lists of `Result`s. If you're familiar with `Promise.all`, the combine function works conceptually the same. `combine` works on both heterogeneous and homogeneous lists. Note that you cannot combine lists that contain both `Result`s and `ResultAsync`s. If all the results in the list are `Ok`, then the return value will be a `Ok` containing a list of all the individual `Ok` values. If just one of the results in the list is an `Err` then the combine function returns that Err value (it short circuits and returns the first Err that it finds). ### Formally speaking: ```typescript // homogeneous lists function combine(resultList: Result[]): Result // heterogeneous lists function combine(resultList: [ Result, Result ]): Result<[ T1, T2 ], E1 | E2> // ... etc ``` ### Example: ```typescript import { Result, ok } from 'neverthrow' const resultList: Result[] = [ok(1), ok(2)] const combinedList: Result = Result.combine(resultList) // Example with tuples: const tuple = (...args: T): T => args const resultTuple: [Result, Result] = tuple(ok('a'), ok('b')) const combinedTuple: Result<[string, string], unknown> = Result.combine(resultTuple) ``` ``` -------------------------------- ### Asynchronous safeTry with Async Generator Functions Source: https://github.com/supermacro/neverthrow/blob/master/README.md Illustrates how to use safeTry with asynchronous generator functions to handle Promises of Results or ResultAsync. It shows the use of `await` for Promises and direct `yield*` for ResultAsync, simplifying async error propagation. ```typescript // You can use either Promise or ResultAsync. declare function mayFail1(): Promise>; declare function mayFail2(): ResultAsync; function myFunc(): Promise> { return safeTry(async function*() { return ok( (yield* (await mayFail1()) .mapErr(e => `aborted by an error from 1st function, ${e}`)) + (yield* mayFail2() .mapErr(e => `aborted by an error from 2nd function, ${e}`)) ) }) } ``` -------------------------------- ### TypeScript: Throwing Exceptions in Asynchronous Functions Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Demonstrates a typical asynchronous function in TypeScript that uses the 'throw' keyword to handle invalid input, which can lead to runtime errors if not caught. ```typescript type ResponseBody = {} interface ResponseData { statusCode: number responseBody?: ResponseBody } const isUrl = (url: string): boolean => { // Dummy implementation for example return url.startsWith('http'); } const makeHttpRequest = async (url: string): Promise => { if (!isUrl(url)) { throw new Error( 'Invalid string passed into `makeHttpRequest`. Expected a valid URL.' ) } // ... // other business logic here // ... return { statusCode: 200 } // ResponseData } ``` -------------------------------- ### Result.combine Source: https://context7.com/supermacro/neverthrow/llms.txt Combines an array of Results into a single Result containing an array of values, short-circuiting on the first error encountered. ```APIDOC ## STATIC Result.combine ### Description Combines an array of Results into a single Result containing an array of values. If any Result is an Err, returns the first Err encountered (short-circuits). ### Method Static Method ### Parameters #### Arguments - **results** (Array>) - Required - An array of Result objects to combine. ### Request Example Result.combine([ok(1), ok(2), ok(3)]) ### Response #### Success Response - **Result, E>** - A Result containing the array of values if all succeeded. #### Error Response - **Result, E>** - A Result containing the first encountered error. ``` -------------------------------- ### ResultAsync.combine: Aggregate multiple ResultAsync operations Source: https://github.com/supermacro/neverthrow/blob/master/README.md The combine static method aggregates a list of ResultAsync operations, similar to Promise.all. It supports both homogeneous and heterogeneous lists. If all operations succeed, it returns an Ok with a list or tuple of their results. If any operation fails, it short-circuits and returns the first Err encountered. ```typescript // homogeneous lists function combine(resultList: ResultAsync[]): ResultAsync // heterogeneous lists function combine(resultList: [ ResultAsync, ResultAsync ]): ResultAsync<[ T1, T2 ], E1 | E2> function combine => ResultAsync<[ T1, T2, T3 ], E1 | E2 | E3> function combine => ResultAsync<[ T1, T2, T3, T4 ], E1 | E2 | E3 | E4> // ... etc etc ad infinitum const resultList: ResultAsync[] = [okAsync(1), okAsync(2)] const combinedList: ResultAsync = ResultAsync.combine(resultList) /** @example tuple(1, 2, 3) === [1, 2, 3] // with type [number, number, number] */ const tuple = (...args: T): T => args const resultTuple: [ResultAsync, ResultAsync] = tuple(okAsync('a'), okAsync('b')) const combinedTuple: ResultAsync<[string, string], unknown> = ResultAsync.combine(resultTuple) ``` -------------------------------- ### Create Async Success with okAsync Source: https://context7.com/supermacro/neverthrow/llms.txt Creates a ResultAsync containing an Ok value. It is the asynchronous equivalent of the ok function. ```typescript import { okAsync, ResultAsync } from 'neverthrow' const asyncResult = okAsync(42) const result = await asyncResult console.log(result._unsafeUnwrap()) // 42 ``` -------------------------------- ### Create ResultAsync from Promise (TypeScript) Source: https://github.com/supermacro/neverthrow/blob/master/README.md Transforms a `PromiseLike` into a `ResultAsync`. It takes a promise and an error handler function that maps any rejection reason (unknown) into a specific error type `E`. ```typescript import { ResultAsync } from 'neverthrow' import { insertIntoDb } from 'imaginary-database' // insertIntoDb(user: User): Promise const res = ResultAsync.fromPromise(insertIntoDb(myUser), () => new Error('Database error')) // `res` has a type of ResultAsync ``` -------------------------------- ### TypeScript: Implementing Custom Result Type for Error Handling Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Shows the definition of a generic Result type in TypeScript, along with helper functions 'ok' and 'err' to create success and failure instances, respectively. This approach encodes potential failures into the type system. ```typescript type Result = Ok // contains a success value of type T | Err // contains a failure value of type E class Ok { constructor(private readonly value: T) {} isOk(): this is Ok { return true; } isErr(): this is Err { return false; } getValue(): T { return this.value; } } class Err { constructor(private readonly error: E) {} isOk(): this is Ok { return false; } isErr(): this is Err { return true; } getError(): E { return this.error; } } // utility functions to build Ok and Err instances const ok = (value: T): Result => new Ok(value) const err = (error: E): Result => new Err(error) ``` -------------------------------- ### Result.match Source: https://context7.com/supermacro/neverthrow/llms.txt Pattern matches on a Result, executing one of two callbacks based on whether it's Ok or Err. ```APIDOC ## Result.match ### Description Pattern matches on a Result, executing one of two callbacks based on whether it's Ok or Err. Unlike map/mapErr, match unwraps the Result and returns the callback's return value directly. ### Method Instance Method ### Parameters - **okCallback** (function) - Required - Function executed if the result is Ok. - **errCallback** (function) - Required - Function executed if the result is Err. ### Response - **T** (any) - The return value of the executed callback. ``` -------------------------------- ### ResultAsync.andThen Source: https://context7.com/supermacro/neverthrow/llms.txt Chains asynchronous operations that return Results, allowing for sequential execution where subsequent steps depend on the success of previous ones. ```APIDOC ## ResultAsync.andThen ### Description Chains async Result-returning operations. The callback can return either a Result or ResultAsync, and the return type is always ResultAsync. Error at any step short-circuits the chain. ### Method Instance Method ### Endpoint ResultAsync.prototype.andThen(callback) ### Parameters #### Request Body - **callback** (function) - Required - A function that takes the success value and returns a Result or ResultAsync. ### Request Example resultAsync.andThen(value => okAsync(value * 2)) ### Response #### Success Response (200) - **ResultAsync** (object) - A new ResultAsync instance containing the result of the chained operation. ``` -------------------------------- ### Handling errors with mapErr Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Shows how to use the .mapErr method to handle failure cases within a Result object. ```typescript import { makeHttpRequest } from './http-api.ts' const run = async () => { const result = await makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1') result.mapErr(errorInstance => { console.log(errorInstance) }) } run() ``` -------------------------------- ### Result.asyncAndThen Source: https://github.com/supermacro/neverthrow/blob/master/README.md Similar to `andThen`, but designed for asynchronous operations, expecting the callback to return a `ResultAsync`. ```APIDOC ## Result.asyncAndThen (method) ### Description Chains asynchronous operations on a Result. The callback function must return a `ResultAsync`, allowing for sequential asynchronous computations that may fail. ### Method `asyncAndThen(callback: (value: T) => ResultAsync): ResultAsync` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming ResultAsync is defined elsewhere // import { ResultAsync } from 'neverthrow' // const asyncOperation = async (value: number): Promise> => { // // ... async logic ... // return ok(value * 2); // }; // ok(5) // .asyncAndThen(asyncOperation) // Returns a ResultAsync // .then(result => console.log(result)); ``` ### Response #### Success Response (200) Returns a `ResultAsync` containing the transformed value or the propagated error from the asynchronous operation. ``` -------------------------------- ### ResultAsync.fromPromise Source: https://github.com/supermacro/neverthrow/blob/master/README.md Transforms a Promise into a ResultAsync, handling potential rejections. ```APIDOC ## ResultAsync.fromPromise ### Description Converts a PromiseLike object into a ResultAsync. It requires an error handler function to transform unknown rejection errors into a specific error type. ### Method Static Method ### Parameters - **promise** (PromiseLike) - Required - The promise to wrap. - **errorHandler** ((unknown) => E) - Required - A function to map the rejection reason to the desired error type. ### Response - **ResultAsync** - A ResultAsync instance representing the outcome of the promise. ``` -------------------------------- ### Handling Results with ResultAsync.match Source: https://github.com/supermacro/neverthrow/blob/master/README.md The match method allows for handling both the success (Ok) and error (Err) variants of a ResultAsync. It takes two callback functions, one for each variant, and executes the appropriate one. Unlike its synchronous counterpart, match on ResultAsync always returns a Promise due to the asynchronous nature of the operations. ```typescript import { Result, ResultAsync } from 'neverthrow'; // Assume validateUser and insertUser have the following signatures: // validateUser(user: User): Result // insertUser(user): ResultAsync const resultMessage = await validateUser(user) .andThen(insertUser) .match( (user: User) => `User ${user.name} has been successfully created`, (error: Error) => `User could not be created because ${error.message}` ); // resultMessage is a string ``` -------------------------------- ### Testing Neverthrow Results with _unsafeUnwrap Source: https://context7.com/supermacro/neverthrow/llms.txt This snippet shows how to use `_unsafeUnwrap` and `_unsafeUnwrapErr` to test Result types from the neverthrow library. These methods are useful for making clear assertions in tests, throwing an error if the Result is not the expected variant. It covers testing both successful Ok values and Err values, as well as direct comparison of Result objects. ```typescript import { ok, err, Result } from 'neverthrow' import { expect, test } from 'vitest' // Test Ok values test('successful operation returns correct value', () => { const result = calculateSum([1, 2, 3]) expect(result.isOk()).toBe(true) expect(result._unsafeUnwrap()).toBe(6) }) // Test Err values test('invalid input returns error', () => { const result = validateEmail('not-an-email') expect(result.isErr()).toBe(true) expect(result._unsafeUnwrapErr()).toBe('Invalid email format') }) // Results are comparable with toEqual test('results are directly comparable', () => { const result = divide(10, 2) expect(result).toEqual(ok(5)) const errorResult = divide(10, 0) expect(errorResult).toEqual(err('Division by zero')) }) // Testing async results test('async operation succeeds', async () => { const result = await fetchUser('123') expect(result.isOk()).toBe(true) expect(result._unsafeUnwrap()).toMatchObject({ id: '123', name: expect.any(String) }) }) ``` -------------------------------- ### Asynchronous Result Handling with ResultAsync Source: https://github.com/supermacro/neverthrow/wiki/Basic-Usage-Examples Shows how to wrap asynchronous operations into ResultAsync objects. It demonstrates using errAsync for synchronous error injection and ResultAsync.fromPromise for handling promise-based operations with custom error mapping. ```typescript import { errAsync, ResultAsync } from 'neverthrow' function addUserToDatabase(user: User): ResultAsync { if (user.name.length < 3) { return errAsync(new Error('Username is too short')) } return ResultAsync.fromPromise(insertIntoDb(user), () => new Error('Database error')) } const asyncRes = addUserToDatabase({ name: 'Tom' }) const asyncRes2 = asyncRes.map((user: User) => user.name) const res = await asyncRes if (res.isErr()) { console.log('Oops fail: ' + res.error.message) } else { console.log('Successfully inserted user ' + res.value) } ``` -------------------------------- ### Pattern Matching with Result.match Source: https://context7.com/supermacro/neverthrow/llms.txt Pattern matches on a Result, executing one of two provided callbacks based on whether the Result is Ok or Err. Unlike map or mapErr, match unwraps the Result and directly returns the value produced by the chosen callback. ```typescript import { ok, err, Result } from 'neverthrow' // Basic pattern matching const result: Result = ok(42) const message = result.match( value => `Success: ${value}`, error => `Error: ${error}` ) console.log(message) // 'Success: 42' // Match on error const errorResult: Result = err('failed') const errorMessage = errorResult.match( value => `Got ${value}`, error => `Oops: ${error}` ) console.log(errorMessage) // 'Oops: failed' // Real-world: HTTP response handling interface User { id: number; name: string } function handleUserResult(result: Result): Response { return result.match( user => ({ status: 200, body: JSON.stringify(user) }), error => ({ status: 400, body: JSON.stringify({ error }) }) ) } const userResult = ok({ id: 1, name: 'Alice' }) const response = handleUserResult(userResult) console.log(response) // { status: 200, body: '{"id":1,"name":"Alice"}' } ``` -------------------------------- ### ResultAsync.fromSafePromise Source: https://github.com/supermacro/neverthrow/blob/master/README.md Creates a ResultAsync from a promise that is guaranteed not to reject, or where rejection is handled externally. ```APIDOC ## ResultAsync.fromSafePromise ### Description Creates a ResultAsync instance from a promise. Note: This does not handle promise rejections; if the promise throws, the ResultAsync will reject. ### Method Static Method ### Parameters #### Request Body - **promise** (PromiseLike) - Required - The promise to wrap into a ResultAsync. ### Request Example ResultAsync.fromSafePromise(new Promise((resolve) => resolve(value))) ### Response #### Success Response (200) - **ResultAsync** - A new ResultAsync instance. ``` -------------------------------- ### Chaining operations with ResultAsync.andThen Source: https://github.com/supermacro/neverthrow/blob/master/README.md The andThen method chains asynchronous operations where each subsequent operation depends on the success of the previous one. It takes a callback function that must return a Result or ResultAsync, and it always returns a ResultAsync. This is useful for sequential computations that might fail, effectively flattening nested ResultAsync structures. ```typescript import { Result, ResultAsync } from 'neverthrow'; // Assume validateUser, insertUser and sendNotification have the following signatures: // validateUser(user: User): Result // insertUser(user): ResultAsync // sendNotification(user): ResultAsync const resAsync = validateUser(user) .andThen(insertUser) .andThen(sendNotification); // resAsync is a ResultAsync resAsync.then((res: Result) => { if(res.isErr()){ console.log("Oops, at least one step failed", res.error) } else{ console.log("User has been validated, inserted and notified successfully.") } }) ``` -------------------------------- ### Wrap Promise with ResultAsync using fromPromise Source: https://github.com/supermacro/neverthrow/wiki/Working-with-ResultAsync This snippet shows how to convert a standard JavaScript Promise into a Neverthrow `ResultAsync`. It highlights the use of a callback function to transform any potential error into a structured error object, ensuring type safety for the error in the `ResultAsync`. ```typescript const userPromise = prisma.user.findUnique(...) const result = fromPromise(userPromise, err => ({err, message: "Some error happened while reading DB"})) ``` -------------------------------- ### Transform Ok value with Result.map Source: https://context7.com/supermacro/neverthrow/llms.txt Shows how to use the `map` method on a `Result` to transform its success value. If the Result is 'Ok', the provided function is applied to the value; otherwise, the 'Err' value is passed through unchanged. This enables functional chaining of operations. ```typescript import { ok, err, Result } from 'neverthrow' // Map over an Ok value const result = ok(5) const doubled = result.map(x => x * 2) console.log(doubled._unsafeUnwrap()) // 10 // Chain multiple maps const processed = ok(' hello world ') .map(str => str.trim()) .map(str => str.toUpperCase()) .map(str => str.split(' ')) console.log(processed._unsafeUnwrap()) // ['HELLO', 'WORLD'] // Map is skipped for Err values const errorResult: Result = err('failed') const mapped = errorResult.map(x => x * 2) console.log(mapped.isErr()) // true console.log(mapped._unsafeUnwrapErr()) // 'failed' (unchanged) // Real-world example: parsing and transforming data function parseUserId(input: string): Result { const id = parseInt(input, 10) return isNaN(id) ? err('Invalid user ID') : ok(id) } const userIdResult = parseUserId('42') .map(id => ({ userId: id, timestamp: Date.now() })) console.log(userIdResult._unsafeUnwrap()) // { userId: 42, timestamp: 1699... } ``` -------------------------------- ### Result.andThen Source: https://context7.com/supermacro/neverthrow/llms.txt Chains Result-returning operations together, enabling sequential computations where each step may fail. It flattens nested Results to prevent complex structures. ```APIDOC ## Result.andThen ### Description Chains Result-returning operations together, enabling sequential computations where each step may fail. Unlike `map`, the callback must return a new `Result`, which is then flattened. ### Method Instance Method ### Parameters - **callback** (function) - Required - A function that takes the success value and returns a new Result. ### Request Example result.andThen(value => nextOperation(value)) ### Response - **Result** (Result) - The result of the chained operation or the first encountered error. ``` -------------------------------- ### Implement Rust-style Error Handling with safeTry Source: https://context7.com/supermacro/neverthrow/llms.txt Uses generator functions to provide a '?' operator-like syntax for early returns on errors. Supports both synchronous and asynchronous workflows. ```typescript import { safeTry, ok, err, okAsync, errAsync, Result, ResultAsync } from 'neverthrow' function calculateTotal(items: Item[]): Result { return safeTry(function* () { const validated = yield* validateItems(items) const prices = yield* fetchPrices(validated) const total = prices.reduce((sum, p) => sum + p, 0) return ok(total) }) } async function processOrder(orderId: string): ResultAsync { return safeTry(async function* () { const order = yield* await fetchOrder(orderId) const validated = yield* validateOrder(order) const payment = yield* await processPayment(validated) const receipt = yield* await generateReceipt(payment) return ok(receipt) }) } ``` -------------------------------- ### Result.fromThrowable Source: https://context7.com/supermacro/neverthrow/llms.txt Wraps a function that might throw into a function that returns a Result. This is essential for integrating with third-party libraries that use exceptions. ```APIDOC ## Result.fromThrowable ### Description Wraps a function that might throw into a function that returns a Result. This is essential for integrating with third-party libraries that use exceptions. ### Method `Result.fromThrowable(fn, errorMapper)` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Result, fromThrowable } from 'neverthrow' // Wrap JSON.parse to return Result instead of throwing const safeJsonParse = fromThrowable( JSON.parse, (e) => `Parse error: ${e instanceof Error ? e.message : 'Unknown error'}` ) const validJson = safeJsonParse('{"name": "Alice"}') console.log(validJson._unsafeUnwrap()) // { name: 'Alice' } const invalidJson = safeJsonParse('not json') console.log(invalidJson._unsafeUnwrapErr()) // 'Parse error: Unexpected token...' // Wrap any throwing function function riskyOperation(x: number): number { if (x < 0) throw new Error('Negative numbers not allowed') return Math.sqrt(x) } const safeSqrt = fromThrowable(riskyOperation, () => 'Invalid input') console.log(safeSqrt(16)._unsafeUnwrap()) // 4 console.log(safeSqrt(-1)._unsafeUnwrapErr()) // 'Invalid input' // With typed error handling interface ParseError { message: string; position?: number } const safeParseTyped = Result.fromThrowable( JSON.parse, (e): ParseError => ({ message: String(e) }) ) ``` ### Response #### Success Response (200) N/A (Static method, returns a function that returns a Result) #### Response Example N/A ``` -------------------------------- ### ResultAsync.unwrapOr Source: https://github.com/supermacro/neverthrow/blob/master/README.md Unwraps the Ok value or returns a default value if the result is an Err. ```APIDOC ## ResultAsync.unwrapOr ### Description Returns the contained Ok value, or a provided default value if the ResultAsync is an Err. ### Method Instance Method ### Parameters #### Request Body - **value** (T) - Required - The default value to return if the result is an Err. ### Request Example resultAsync.unwrapOr(defaultValue) ### Response #### Success Response (200) - **Promise** - The unwrapped value or the default value. ``` -------------------------------- ### ResultAsync.andThrough Source: https://github.com/supermacro/neverthrow/blob/master/README.md Chains an operation that can potentially return an error, propagating that error if it occurs. ```APIDOC ## ResultAsync.andThrough ### Description Similar to andTee, but if the provided callback returns an error, that error is propagated and returned by the ResultAsync chain. ### Method Instance Method ### Parameters #### Request Body - **callback** (function) - Required - A function that takes the success value and returns a Result or ResultAsync. ### Request Example resAsync.andThrough(insertUser) ### Response #### Success Response (200) - **ResultAsync** - Returns a new ResultAsync containing the original value or the new error. ``` -------------------------------- ### Result.andThrough Source: https://context7.com/supermacro/neverthrow/llms.txt Similar to andTee, but if the side effect function returns an Err, that error propagates. Useful for validation or side effects that can fail and should abort the pipeline. ```APIDOC ## Result.andThrough ### Description Similar to andTee, but if the side effect function returns an Err, that error propagates. Useful for validation or side effects that can fail and should abort the pipeline. ### Method N/A (Instance method on Result) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { ok, err, Result } from 'neverthrow' // Side effect that can fail function validateUser(user: User): Result { return user.age >= 18 ? ok(undefined) : err('User must be 18+') } const result = ok({ name: 'Bob', age: 16 }) .andThrough(validateUser) // Returns error .map(user => user.name) console.log(result._unsafeUnwrapErr()) // 'User must be 18+' // Success path - original value passes through const adultResult = ok({ name: 'Alice', age: 25 }) .andThrough(validateUser) // Returns ok, original value continues .map(user => user.name) console.log(adultResult._unsafeUnwrap()) // 'Alice' // Real-world: save to database then continue with original data function saveToDb(user: User): Result { return ok(undefined) // Simulated successful save } const pipeline = ok({ id: 1, name: 'Alice' }) .andThrough(saveToDb) // Save, but keep original user object .andThen(user => sendWelcomeEmail(user)) // user still available ``` ### Response #### Success Response (200) N/A (Instance method, returns the modified Result) #### Response Example N/A ``` -------------------------------- ### safeTry Source: https://context7.com/supermacro/neverthrow/llms.txt Enables Rust-style '?' operator semantics using generator functions to reduce boilerplate in complex synchronous or asynchronous operations. ```APIDOC ## safeTry ### Description Enables Rust-style '?' operator semantics using generator functions. Allows early return on errors while maintaining type safety. ### Method Function ### Endpoint safeTry(generatorFunction) ### Parameters #### Request Body - **generatorFunction** (function) - Required - A generator function that yields Results or ResultAsyncs. ### Request Example safeTry(function* () { const val = yield* operation(); return ok(val); }) ### Response #### Success Response (200) - **Result | ResultAsync** (object) - The final Result returned from the generator function. ``` -------------------------------- ### Result.andThen Source: https://github.com/supermacro/neverthrow/blob/master/README.md Chains operations on a Result that may also fail. It allows returning a new Result, potentially with a different error type. ```APIDOC ## Result.andThen (method) ### Description Chains operations on a Result that may also fail. It allows returning a new Result, potentially with a different error type. Useful for subsequent computations that might fail or for flattening nested Results. ### Method `andThen(callback: (value: T) => Result): Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { err, ok } from 'neverthrow' const sq = (n: number): Result => ok(n ** 2) ok(2) .andThen(sq) .andThen(sq) // Ok(16) ok(2) .andThen(sq) .andThen(err) // Err(4) ok(2) .andThen(err) .andThen(sq) // Err(2) err(3) .andThen(sq) .andThen(sq) // Err(3) // Flattening nested Results const nested = ok(ok(1234)) const notNested = nested.andThen((innerResult) => innerResult) // Ok(1234) ``` ### Response #### Success Response (200) Returns a new Result containing the transformed value or the propagated error. #### Response Example ```json // Example for Ok(16) from the chaining example { "value": 16 } // Example for Err(4) from the chaining example { "error": 4 } ``` ``` -------------------------------- ### Chaining Result operations Source: https://github.com/supermacro/neverthrow/wiki/Introduction:-Type-Safe-Errors-in-JS-&-TypeScript-(10-minute-read) Illustrates the chainable nature of Result objects by combining map and mapErr to handle both success and failure states in a single flow. ```typescript import { makeHttpRequest } from './http-api.ts' const run = async () => { const result = await makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1') result .map(responseData => { // do something with the success value }) .mapErr(errorInstance => { // do something with the failure value }) } run() ```