### Install ts-results-es with yarn Source: https://github.com/lune-climate/ts-results-es/blob/master/README.md Use this command to install the package using yarn. ```bash $ yarn add ts-results-es ``` -------------------------------- ### Install ts-results-es with npm Source: https://github.com/lune-climate/ts-results-es/blob/master/README.md Use this command to install the package using npm. ```bash $ npm install ts-results-es ``` -------------------------------- ### AsyncOption or Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Use or to provide a default value if the AsyncOption is None. The default value can be a synchronous Option or another AsyncOption. ```typescript const noValue = new AsyncOption(None) const hasValue = new AsyncOption(Some(1)) await noValue.or(Some(123)).promise // Some(123) await hasValue.or(Some(123)).promise // Some(1) ``` -------------------------------- ### AsyncResult or Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Illustrates the `or` method, which returns the `AsyncResult` itself if it's Ok, or the provided `other` Result/AsyncResult if the current `AsyncResult` is Err. This is useful for providing a default value when an operation fails. ```typescript const badResult = new AsyncResult(Err('Error message')) const goodResult = new AsyncResult(Ok(1)) await badResult.or(Ok(123)).promise // Ok(123) await goodResult.or(Ok(123)).promise // Ok(1) ``` -------------------------------- ### AsyncResult orElse Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Shows the `orElse` method, which is similar to `or` but takes a function that is only called if the `AsyncResult` is Err. This allows for lazy evaluation of the alternative Result, which can be more performant if the alternative is computationally expensive. ```typescript const badResult = new AsyncResult(Err('Error message')) const goodResult = new AsyncResult(Ok(1)) await badResult.orElse(() => Ok(123)).promise // Ok(123) await goodResult.orElse(() => Ok(123)).promise // Ok(1) ``` -------------------------------- ### AsyncResult map Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Shows how to use the `map` method to transform the Ok value of an AsyncResult. If the AsyncResult is Ok, the provided mapper function is applied to the value; otherwise, the Err value is preserved. The mapper function can be asynchronous. ```typescript let goodResult = Ok(1).toAsyncResult() let badResult = Err('boo').toAsyncResult() await goodResult.map(async (value) => value * 2).promise // Ok(2) await badResult.andThen(async (value) => value * 2).promise // Err('boo') ``` -------------------------------- ### AsyncResult andThen Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Illustrates the `andThen` method for chaining operations on an AsyncResult. It applies a function to the Ok value if the AsyncResult is Ok, or propagates the Err value. The function passed to `andThen` can return a Result, a Promise of a Result, or an AsyncResult. ```typescript let goodResult = Ok(1).toAsyncResult() let badResult = Err('boo').toAsyncResult() await goodResult.andThen(async (value) => Ok(value * 2)).promise // Ok(2) await goodResult.andThen(async (value) => Err(`${value} is bad`)).promise // Err('1 is bad') await badResult.andThen(async (value) => Ok(value * 2)).promise // Err('boo') ``` -------------------------------- ### AsyncOption andThen Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Use andThen to chain operations on an AsyncOption. It applies a mapper function if the option is Some, otherwise it preserves the None value. The mapper can return an Option, a Promise of an Option, or an AsyncOption. ```typescript let hasValue = Some(1).toAsyncOption() let noValue = None.toAsyncOption() await hasValue.andThen(async (value) => Some(value * 2)).promise // Some(2) await hasValue.andThen(async (value) => None).promise // None await noValue.andThen(async (value) => Some(value * 2)).promise // None ``` -------------------------------- ### AsyncResult mapErr Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Demonstrates the `mapErr` method for transforming the Err value of an AsyncResult. If the AsyncResult is Err, the provided mapper function is applied to the error; otherwise, the Ok value is preserved. The mapper function can be asynchronous. ```typescript let goodResult = Ok(1).toAsyncResult() let badResult = Err('boo').toAsyncResult() await goodResult.mapErr(async (error) => `Error is ${error}`).promise // Ok(1) await badResult.mapErr(async (error) => `Error is ${error}`).promise // Err('Error is boo') ``` -------------------------------- ### Convert Result to AsyncResult Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Uses the `toAsyncResult()` method on a synchronous Result to convert it into an AsyncResult. This is a convenient way to start an asynchronous chain with an existing synchronous Result. ```typescript const result3 = Ok(1).toAsyncResult() ``` -------------------------------- ### AsyncOption orElse Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Use orElse to provide a default value by calling a function if the AsyncOption is None. The function will only be executed if the AsyncOption is None. The function can return an Option, an AsyncOption, or a Promise of an Option. ```typescript const noValue = new AsyncOption(None) const hasValue = new AsyncOption(Some(1)) await noValue.orElse(() => Some(123)).promise // Some(123) await hasValue.orElse(() => Some(123)).promise // Some(1) ``` -------------------------------- ### Get Ok value or compute with unwrapOrElse Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Use `unwrapOrElse` to get the `Ok` value or compute a new value using a provided function if the Result is `Err`. The function is only called if the Result is `Err`. ```typescript unwrapOrElse(f: (error: E) => T2): T | T2 ``` ```typescript Ok('OK').unwrapOrElse( (error) => { console.log(`Called, got ${error}`); return 'UGH'; } ) // => 'OK', nothing printed Err('A03B').unwrapOrElse((error) => `UGH, got ${error}`) // => 'UGH, got A03B' ``` -------------------------------- ### AsyncOption map Example Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Use map to apply a transformation function to the value inside an AsyncOption if it is Some. The transformation can be asynchronous. If the AsyncOption is None, it remains None. ```typescript let hasValue = Some(1).toAsyncOption() let noValue = None.toAsyncOption() await hasValue.map(async (value) => value * 2).promise // Some(2) await noValue.map(async (value) => value * 2).promise // None ``` -------------------------------- ### Using resultMergeMap with RxJS Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/rxjs.md Demonstrates how `resultMergeMap` can be used to flatten a stream of Results into another stream, handling potential type changes and error propagation. The example shows merging results from two different observable streams. ```typescript import { of, Observable } from 'rxjs'; import { Ok, Err, Result } from 'ts-results-es'; import { resultMergeMap } from 'ts-results-es/rxjs-operators'; const obs$: Observable> = of(new Ok(5), new Err(new Error('uh oh'))); const obs2$: Observable> = of(new Ok('hi'), new Err(new CustomError('custom error'))); const test$ = obs$.pipe( resultMergeMap((number) => { console.log('Got number: ' + number); return obs2$; }), ); // Has type Observable> test$.subscribe((result) => { if (result.isOk()) { console.log('Got string: ' + result.value); } else { console.log('Got error: ' + result.error.message); } }); // Logs the following: // Got number: 5 // Got string: hi // Got error: custom error // Got error: uh oh ``` -------------------------------- ### Build and Publish Package Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/dev/index.md Run these commands in sequence to build the package and then publish it to the npm registry. Ensure versioning and Git tags are handled prior to execution. ```bash npm run build && npm publish ``` -------------------------------- ### Constructing Result Instances Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Shows how to create instances of Ok for success and Err for failure. ```typescript const success = Ok('my username') const error = Err('error_code') ``` -------------------------------- ### AsyncOption Construction Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Demonstrates how to construct an AsyncOption directly from an Option or a Promise of an Option, or by using the Option.toAsyncOption() method. ```APIDOC ## Construction You can construct it directly from `Option` or `Promise>`: ```typescript const option1 = new AsyncOption(Some(1)) const option2 = new AsyncOption((async () => None)()) ``` Or you can use the [Option.toAsyncOption()](option.md#method-option-toasyncoption) method: ```typescript const option3 = Some(1).toAsyncOption() ``` ``` -------------------------------- ### Extract Ok Type from Result Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Use `ResultOkType` to get the success type from a single Result. This is useful for defining types that expect a successful outcome. ```typescript type ResultOkType> ``` -------------------------------- ### Extract Err Type from Result Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Use `ResultErrType` to get the error type from a single Result. This is useful for defining types that handle potential errors. ```typescript type ResultErrType> ``` -------------------------------- ### AsyncResult Construction Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Demonstrates how to construct an AsyncResult directly from a Result or a Promise of a Result, or by using the Result.toAsyncResult() method. ```APIDOC ## Construction You can construct it directly from `Result` or `Promise>`: ```typescript const result1 = new AsyncResult(Ok(1)) const result2 = new AsyncResult((async () => Err('bad_error')()) ``` Or you can use the `[Result.toAsyncResult()](result.md#method-result-toasyncresult)` method: ```typescript const result3 = Ok(1).toAsyncResult() ``` ``` -------------------------------- ### Option.all() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Parses an array of Options, returning an array of all Some values. Short-circuits with the first None found. ```APIDOC ## `all()` ### Description Parses a set of `Option`’s, returning an array of all `Some` values. Short circuits with the first `None` found, if any. ### Method `static all[]>(options: T): Option>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript let options: Option[] = [Some(1), Some(2), Some(3)]; Option.all(options); let optionsWithNone: Option[] = [Some(1), None, Some(3)]; Option.all(optionsWithNone); ``` ### Response #### Success Response (200) `Option>`: Contains an array of `Some` values if all inputs are `Some`, otherwise `None`. #### Response Example ```json // For [Some(1), Some(2), Some(3)] Some([1, 2, 3]) // For [Some(1), None, Some(3)] None ``` ``` -------------------------------- ### unwrapOrElse Method for Option Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Use `unwrapOrElse` to get the contained value of a `Some` or compute a default value using a function if the Option is `None`. The provided function is executed at most once, only when the Option is `None`. ```typescript unwrapOrElse(f: () => T2): T | T2 ``` ```typescript Some('OK').unwrapOrElse( () => { console.log('Called'); return 'UGH'; } ) // => 'OK', nothing printed None.unwrapOrElse(() => 'UGH') // => 'UGH' ``` -------------------------------- ### Some.EMPTY - Singleton for Option Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Represents a Some instance containing undefined, useful for indicating success without a specific value. ```typescript const x: Option = Some.EMPTY ``` -------------------------------- ### Ok.EMPTY Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md A static Ok instance containing undefined. Useful for representing a success without a specific value. ```APIDOC ## Ok.EMPTY ### Description A static `Ok` instance containing `undefined`. Useful when you need to represent a success without a meaningful value. ### Method `static readonly EMPTY: Ok` ### Request Example ```typescript const x: Result = Ok.EMPTY ``` ### Response #### Success Response - **EMPTY**: Ok - A predefined Ok instance with an undefined value. ### Response Example ```typescript // Ok(undefined) ``` ``` -------------------------------- ### then() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Implements the thenable interface, making AsyncOption directly awaitable and allowing it to be used with async/await syntax. ```APIDOC ## `then()` ```typescript then, TResult2 = never>( onfulfilled?: ((value: Option) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise ``` Makes `AsyncOption` awaitable by implementing the thenable interface. This allows you to use `await` directly on `AsyncOption` instances. See the [Promise.then() documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) for details on the thenable interface. Example: ```typescript const asyncOption = new AsyncOption(Some(42)) const option = await asyncOption // Returns Option ``` ``` -------------------------------- ### isOk() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md `true` when the result is `Ok`. ```APIDOC ## `isOk(): this is Ok` `true` when the result is `Ok`. ``` -------------------------------- ### Result.partition() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Partitions a set of Results into two arrays: one containing all Ok values and the other containing all Err values. ```APIDOC ## Result.partition() ### Description Partitions a set of `Result`, separating the `Ok` and `Err` values into two distinct arrays. ### Method `static partition(results: Result[]): [T[], E[]]` ### Parameters - **results** (Result[]): An array of Result objects. ### Request Example ```typescript let results: Result[] = [Ok(1), Err('error1'), Ok(2), Err('error2')]; let [numbers, errors] = Result.partition(results); // [ [1, 2], ['error1', 'error2'] ] ``` ### Response #### Success Response - **partition**: [T[], E[]] - A tuple containing two arrays: the first with all Ok values, and the second with all Err values. ### Response Example ```typescript // For input [Ok(1), Err('error1'), Ok(2), Err('error2')], the output is [[1, 2], ['error1', 'error2']]. ``` ``` -------------------------------- ### Get Ok value or default with unwrapOr Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Use `unwrapOr` to retrieve the contained value if it's `Ok`, otherwise return a specified default value. This is useful when you need a fallback value for `Err` variants. ```typescript unwrapOr(val: T2): T | T2 ``` ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.unwrapOr(5); // 1 badResult.unwrapOr(5); // 5 ``` -------------------------------- ### stack Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md A stack trace is generated when an Err is created. ```APIDOC ## `stack` A stack trace is generated when an `Err` is created. ```typescript let error = Err('Uh Oh'); let stack = error.stack; ``` ``` -------------------------------- ### Option.any() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Parses an array of Options, short-circuiting when an input value is Some. Returns the first Some value found, or None if no Some values exist. ```APIDOC ## `any()` ### Description Parses a set of `Option`’s, short-circuits when an input value is `Some`. If no `Some` is found, returns `None`. ### Method `static any[]>(options: T): Option[number]>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript let options: Option[] = [None, Some(1), Some(2)]; Option.any(options); Option.any([None, None, Some(3)]); Option.any([None, None, None]); ``` ### Response #### Success Response (200) `Option[number]>`: The first `Some` value encountered, or `None` if all inputs are `None`. #### Response Example ```json // For [None, Some(1), Some(2)] Some(1) // For [None, None, Some(3)] Some(3) // For [None, None, None] None ``` ``` -------------------------------- ### or() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the Option if it is Some, otherwise returns the other provided Option. The other Option is evaluated eagerly. ```APIDOC ## `or()` ```typescript or(other: Option): Option ``` Returns `Some()` if we have a value, otherwise returns `other`. `other` is evaluated eagerly. If `other` is a result of a function call try [orElse()]() instead – it evaluates the parameter lazily. Example: ```typescript Some(1).or(Some(2)) // => Some(1) None.or(Some(2)) // => Some(2) ``` ``` -------------------------------- ### Construct AsyncResult from Result or Promise Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Demonstrates creating an AsyncResult instance directly from a synchronous Result or a Promise that resolves to a Result. This is useful when you have an existing Result or a function that returns a Promise of a Result. ```typescript const result1 = new AsyncResult(Ok(1)) const result2 = new AsyncResult((async () => Err('bad_error')()) ``` -------------------------------- ### `then()` Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Implements the thenable interface, allowing AsyncResult to be used with `await`. It takes optional `onfulfilled` and `onrejected` callbacks, similar to `Promise.then()`. ```APIDOC ## `then()` ### Description Implements the thenable interface, allowing `AsyncResult` to be used with `await`. It takes optional `onfulfilled` and `onrejected` callbacks, similar to `Promise.then()`. ### Signature ```typescript then, TResult2 = never>( onfulfilled?: ((value: Result) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise ``` ### Example ```typescript const asyncResult = new AsyncResult(Ok(42)) const result = await asyncResult // Returns Result ``` ``` -------------------------------- ### toResult() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Converts the Option into a Result type. If the Option is Some, it becomes Ok(value). If None, it becomes Err(error). ```APIDOC ## `toResult()` ```typescript toResult(error: E): Result ``` Maps an `Option` to a `Result`. ``` -------------------------------- ### or() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns Ok() if we have a value, otherwise returns other. other is evaluated eagerly. ```APIDOC ## `or()` ```typescript or(other: Result): Result ``` Returns `Ok()` if we have a value, otherwise returns `other`. `other` is evaluated eagerly. If `other` is a result of a function try [orElse()]() instead – it evaluates the parameter lazily. Example: ```typescript Ok(1).or(Ok(2)) // => Ok(1) Err('error here').or(Ok(2)) // => Ok(2) ``` ``` -------------------------------- ### Importing Option Types Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Imports necessary types and constructors for using Option. ```typescript import { None, Option, Some } from 'ts-results-es' ``` -------------------------------- ### Import AsyncOption Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Import the AsyncOption class from the ts-results-es library. ```typescript import { AsyncOption } from 'ts-results-es' ``` -------------------------------- ### expect() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the contained Some value, throwing an error if the Option is None. Use this when you are certain a value exists. ```APIDOC ## `expect()` ```typescript expect(msg: string): T ``` Returns the contained `Some` value, if exists. Throws an error if not. If you know you’re dealing with `Some` and the compiler knows it too (because you tested [isSome()]() or [isNone()]()) you should use [value]() instead. While `Some`’s [expect()]() and [value]() will both return the same value using [value]() is preferable because it makes it clear that there won’t be an exception thrown on access. `msg`: the message to throw if no `Some` value. ``` -------------------------------- ### Ok.EMPTY - Static Empty Success Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md A static Ok instance containing undefined. Useful for representing a success without a specific value. ```typescript static readonly EMPTY: Ok ``` ```typescript const x: Result = Ok.EMPTY ``` -------------------------------- ### toAsyncOption() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Converts the current Option into an AsyncOption. Useful for composing with asynchronous operations. ```APIDOC ## `toAsyncOption()` ```typescript toAsyncOption(): AsyncOption ``` Creates an AsyncOption based on this Option. Useful when you need to compose results with asynchronous code. ``` -------------------------------- ### or() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Returns the value from another Option or AsyncOption if the current AsyncOption is None, otherwise returns the current AsyncOption. ```APIDOC ## `or()` ```typescript or(other: Option | AsyncOption | Promise>): AsyncOption ``` Returns the value from `other` if this `AsyncOption` contains `None`, otherwise returns self. If `other` is a result of a function call consider using [orElse()](#method-asyncoption-orelse) instead, it will only evaluate the function when needed. Example: ```typescript const noValue = new AsyncOption(None) const hasValue = new AsyncOption(Some(1)) await noValue.or(Some(123)).promise // Some(123) await hasValue.or(Some(123)).promise // Some(1) ``` ``` -------------------------------- ### toResult() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Converts an AsyncOption to an AsyncResult, mapping None to Err(error) and Some to Ok. ```APIDOC ## `toResult()` ```typescript toResult(error: E): AsyncResult ``` Converts an `AsyncOption` to an `AsyncResult` so that `None` is converted to `Err(error)` and `Some` is converted to `Ok`. ``` -------------------------------- ### isNone() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Checks if the Option is None. Returns true if the Option is None, false otherwise. ```APIDOC ## `isNone()` ```typescript isNone(): this is None ``` `true` when the `Option` is `None`. ``` -------------------------------- ### Iterable Interface Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md `Option` implements the `Iterable` interface, allowing it to be used in `for...of` loops and with spread syntax. ```APIDOC ## Iterable ### Description `Option` implements the `Iterable` interface, allowing you to use it in `for...of` loops and with spread syntax. - `Some` yields its contained value once - `None` yields nothing (empty iterator) ### Example ```typescript for (const value of Some(42)) { console.log(value); // 42 } for (const value of None) { console.log(value); // never executes } [...Some(1)] // [1] [...None] // [] const options = [Some(1), None, Some(3)]; options.flatMap(opt => [...opt]); // [1, 3] ``` ``` -------------------------------- ### Some.EMPTY Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md A static readonly Some instance containing undefined. Useful for representing a successful presence without a meaningful value. ```APIDOC ## `Some.EMPTY` ### Description A static `Some` instance containing `undefined`. Useful when you need to represent a successful presence without a meaningful value. ### Method `static readonly EMPTY: Some` ### Parameters None ### Request Example ```typescript const x: Option = Some.EMPTY ``` ### Response #### Success Response (200) `Some`: A `Some` variant with an `undefined` value. #### Response Example ```json Some(undefined) ``` ``` -------------------------------- ### Import AsyncResult Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Imports the AsyncResult class from the ts-results-es library. Ensure this import is present before using AsyncResult. ```typescript import { AsyncResult } from 'ts-results-es' ``` -------------------------------- ### Option `or` Method Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the Some value if present, otherwise returns the provided `other` Option. The `other` Option is evaluated eagerly. ```typescript or(other: Option): Option ``` ```typescript Some(1).or(Some(2)) // => Some(1) None.or(Some(2)) // => Some(2) ``` -------------------------------- ### unwrap() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the contained Ok value. This function may throw, so its use is generally discouraged. Prefer to handle the Err case explicitly. ```APIDOC ## `unwrap()` ```typescript unwrap(): T ``` Returns the contained `Ok` value. Because this function may throw, its use is generally discouraged. Instead, prefer to handle the `Err` case explicitly. If you know you’re dealing with `Ok` and the compiler knows it too (because you tested [isOk()]() or [isErr()]()) you should use [value]() instead. While `Ok`’s [unwrap()]() and [value]() will both return the same value using [value]() is preferable because it makes it clear that there won’t be an exception thrown on access. Throws if the value is an `Err`, with a message provided by the `Err`’s value and [cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) set to the value. Example: ```typescript let goodResult = new Ok(1); let badResult = new Err(new Error('something went wrong')); goodResult.unwrap(); // 1 badResult.unwrap(); // throws Error("something went wrong") ``` ``` -------------------------------- ### Result.partition() - Separate Ok and Err Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Partitions an array of Results into two arrays: one for Ok values and one for Err values. ```typescript // The actual signature is more complicated but this should be good enough. static partition(results: Result[]): [T[], E[]] ``` ```typescript let results: Result[] = [Ok(1), Err('error1'), Ok(2), Err('error2')]; let [numbers, errors] = Result.partition(results); // [ [1, 2], ['error1', 'error2'] ] ``` -------------------------------- ### Option.any() - Find first Some value Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Processes an array of Options, returning the first Some value encountered. Returns None if all Options are None. ```typescript let options: Option[] = [None, Some(1), Some(2)]; Option.any(options); // Some(1), type: Option ``` ```typescript Option.any([None, None, Some(3)]); // Some(3), type: Option ``` ```typescript Option.any([None, None, None]); // None, type: Option ``` -------------------------------- ### map() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Maps an AsyncResult to a new AsyncResult by applying a function to the Ok value, leaving Err values untouched. Useful for composing functions. ```APIDOC ## `map()` ```typescript map(mapper: (val: T) => U | Promise): AsyncResult ``` ### Description Maps an `AsyncResult` to `AsyncResult` by applying a function to a contained `Ok` value, leaving an `Err` value untouched. This function can be used to compose the results of two functions. ### Example ```typescript let goodResult = Ok(1).toAsyncResult() let badResult = Err('boo').toAsyncResult() await goodResult.map(async (value) => value * 2).promise // Ok(2) await badResult.andThen(async (value) => value * 2).promise // Err('boo') ``` ``` -------------------------------- ### expect() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the contained `Ok` value, if exists. Throws an error if not. The thrown error’s cause is set to the value contained in `Err`. ```APIDOC ## `expect(msg: string): T` Returns the contained `Ok` value, if exists. Throws an error if not. The thrown error’s [cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) is set to value contained in `Err`. If you know you’re dealing with `Ok` and the compiler knows it too (because you tested [isOk()]() or [isErr()]()) you should use [value]() instead. While `Ok`’s [expect()]() and [value]() will both return the same value using [value]() is preferable because it makes it clear that there won’t be an exception thrown on access. `msg`: the message to throw if no Ok value. Example: ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.expect('goodResult should be a number'); // 1 badResult.expect('badResult should be a number'); // throws Error("badResult should be a number - Error: something went wrong") ``` ``` -------------------------------- ### unwrapOr() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the contained Ok value or a provided default value if the Result is an Err. ```APIDOC ## `unwrapOr()` ```typescript unwrapOr(val: T2): T | T2 ``` Returns the contained `Ok` value or a provided default. Example: ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.unwrapOr(5); // 1 badResult.unwrapOr(5); // 5 ``` ``` -------------------------------- ### mapErr() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Maps an AsyncResult to a new AsyncResult by applying a function to the Err value, leaving Ok values untouched. ```APIDOC ## `mapErr()` ```typescript mapErr(mapper: (val: E) => F | Promise): AsyncResult ``` ### Description Maps an `AsyncResult` to `AsyncResult` by applying `mapper` to the `Err` value, leaving `Ok` value untouched. ### Example ```typescript let goodResult = Ok(1).toAsyncResult() let badResult = Err('boo').toAsyncResult() await goodResult.mapErr(async (error) => `Error is ${error}`).promise // Ok(1) await badResult.mapErr(async (error) => `Error is ${error}`).promise // Err('Error is boo') ``` ``` -------------------------------- ### andThen() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Calls a mapper function if the Option is Some, otherwise returns None. Useful for chaining operations that might result in an Option. ```APIDOC ## `andThen()` ```typescript andThen(mapper: (val: T) => Option): Option ``` Calls `mapper` if the `Option` is `Some`, otherwise returns `None`. This function can be used for control flow based on `Option` values. ``` -------------------------------- ### mapOrElse() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Maps the Option to a value using a mapper function for Some or a default function for None. The default function is only called when needed. ```APIDOC ## `mapOrElse()` ```typescript mapOrElse(default_: () => U, mapper: (val: T) => U): U ``` Maps an `Option` to `Option` by either converting `T` to `U` using `mapper` (in case of `Some`) or producing a default value using the `default_` function (in case of `None`). ``` -------------------------------- ### promise Attribute Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Provides a Promise that resolves to a synchronous Option, allowing conversion of AsyncOption to Option. ```APIDOC ## `promise` ```typescript promise: Promise> ``` A promise that resolves to a synchronous `Option`. You can await it to convert `AsyncOption` to `Option`, but prefer awaiting `AsyncOption` directly (see: [then()]()). Only use this property if you need the underlying Promise for specific use cases. ``` -------------------------------- ### Using resultMap Operator with RxJS Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/rxjs.md Demonstrates how to use the `resultMap` operator to transform the Ok value of a Result within an RxJS observable stream. It shows how to handle both Ok and Err cases in the subscription. ```typescript import { of, Observable } from 'rxjs'; import { Ok, Err, Result } from 'ts-results-es'; import { resultMap } from 'ts-results-es/rxjs-operators'; const obs$: Observable> = of(Ok(5), Err('uh oh')); const greaterThanZero = obs$.pipe( resultMap((number) => number > 0), // Return true for values greater zero ); // Has type Observable> greaterThanZero.subscribe((result) => { if (result.isOk()) { console.log('Was greater than zero: ' + result.value); } else { console.log('Got Error Message: ' + result.error); } }); // Logs the following: // Was greater than zero: true // Got Error Message: uh oh ``` -------------------------------- ### Iterable Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Demonstrates how the Result type implements the Iterable interface for use in loops and spread syntax. ```APIDOC ## Iterable `Result` implements the `Iterable` interface, allowing you to use it in `for...of` loops and with spread syntax. - `Ok` yields its contained value once - `Err` yields nothing (empty iterator) Example: ```typescript for (const value of Ok(42)) { console.log(value); // 42 } for (const value of Err('error')) { console.log(value); // never executes } [...Ok(1)] // [1], type: number[] [...Err('oops')] // [], type: never[] const results = [Ok(1), Err('bad'), Ok(3)]; results.flatMap(res => [...res]); // [1, 3], type: number[] ``` ``` -------------------------------- ### `toOption()` Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Converts an `AsyncResult` into an `AsyncOption`. An `Err` value is converted to `None`, and an `Ok` value is converted to `Some`. ```APIDOC ## `toOption()` ### Description Converts from `AsyncResult` to `AsyncOption` so that `Err` is converted to `None` and `Ok` is converted to `Some`. ### Signature ```typescript toOption(): AsyncOption ``` ``` -------------------------------- ### toAsyncResult() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Creates an AsyncResult based on this Result. Useful when you need to compose results with asynchronous code. ```APIDOC ## `toAsyncResult()` ```typescript toAsyncResult(): AsyncResult ``` Creates an AsyncResult based on this Result. Useful when you need to compose results with asynchronous code. ``` -------------------------------- ### Option.all() - Process array of Options Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Processes an array of Options, returning Some containing an array of all contained values if all are Some. Short-circuits and returns None if any Option is None. ```typescript let options: Option[] = [Some(1), Some(2), Some(3)]; Option.all(options); // Some([1, 2, 3]), type: Option ``` ```typescript // Short-circuits on first None let optionsWithNone: Option[] = [Some(1), None, Some(3)]; Option.all(optionsWithNone); // None, type: Option ``` -------------------------------- ### mapOrElse() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Maps a Result to Result by either converting T to U using mapper (in case of Ok) or producing a default value using the default_ function (in case of Err). ```APIDOC ## `mapOrElse()` ```typescript mapOrElse(default_: (error: E) => U, mapper: (val: T) => U): U ``` Maps a `Result` to `Result` by either converting `T` to `U` using `mapper` (in case of `Ok`) or producing a default value using the `default_` function (in case of `Err`). ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.mapOrElse((_error) => 0, (value) => -value) // -1 badResult.mapOrElse((_error) => 0, (value) => -value) // 0 ``` ``` -------------------------------- ### unwrapOr() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the contained Some value or a provided default value if the Option is None. ```APIDOC ## `unwrapOr()` ```typescript unwrapOr(val: T2): T | T2 ``` Returns the contained `Some` value or a provided default. ``` -------------------------------- ### Option `toResult` Method Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Maps an Option to a Result, providing an error value if the Option is None. ```typescript toResult(error: E): Result ``` -------------------------------- ### mapOr() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Maps the Option to a value. If the Option is Some, applies the mapper function. If None, returns the provided default value. ```APIDOC ## `mapOr()` ```typescript mapOr(default_: U, mapper: (val: T) => U): U ``` Maps an `Option` to `Option` by either converting `T` to `U` using `mapper` (in case of `Some`) or using the `default_` value (in case of `None`). If `default_` is a result of a function call consider using [mapOrElse()]() instead, it will only evaluate the function when needed. ``` -------------------------------- ### unwrap() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the contained Some value. Throws an error if the Option is None. Prefer explicit handling over this method. ```APIDOC ## `unwrap()` ```typescript unwrap(): T ``` Returns the contained `Some` value. Because this function may throw, its use is generally discouraged. Instead, prefer to handle the `None` case explicitly. If you know you’re dealing with `Some` and the compiler knows it too (because you tested [isSome()]() or [isNone()]()) you should use [value]() instead. While `Some`’s [unwrap()]() and [value]() will both return the same value using [value]() is preferable because it makes it clear that there won’t be an exception thrown on access. Throws if the value is `None`. ``` -------------------------------- ### Option `toAsyncOption` Method Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Creates an AsyncOption based on the current Option. Useful for composing Option results with asynchronous operations. ```typescript toAsyncOption(): AsyncOption ``` -------------------------------- ### Constructing a Some value Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Creates an Option containing a value. ```typescript const some = Some('some value') ``` -------------------------------- ### Result.all() - Array Overload Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Processes an array of Results, returning an array of all Ok values. Short-circuits on the first Err. ```typescript // Array overload static all(results: Result[]): Result ``` ```typescript let results: Result[] = pizzaToppingNames.map(name => getPizzaToppingByName(name)); let result = Result.all(results); // Result let toppings = result.unwrap(); // toppings is an array of Topping. Could throw GetToppingsError. ``` -------------------------------- ### mapOr() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Maps a Result to Result by either converting T to U using mapper (in case of Ok) or using the default_ value (in case of Err). ```APIDOC ## `mapOr()` ```typescript mapOr(default_: U, mapper: (val: T) => U): U ``` Maps a `Result` to `Result` by either converting `T` to `U` using `mapper` (in case of `Ok`) or using the `default_` value (in case of `Err`). If `default_` is a result of a function call consider using [mapOrElse()]() instead, it will only evaluate the function when needed. Example: ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.mapOr(0, (value) => -value) // -1 badResult.mapOr(0, (value) => -value) // 0 ``` ``` -------------------------------- ### orElse() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Calls a function to provide an alternative AsyncResult or Result if the current AsyncResult is Err, otherwise returns the current AsyncResult. ```APIDOC ## `orElse()` ```typescript orElse( other: (error: E) => Result | AsyncResult | Promise>, ): AsyncResult ``` ### Description Returns the value obtained by calling `other` if this `AsyncResult` contains `Err`, otherwise returns self. ### Example ```typescript const badResult = new AsyncResult(Err('Error message')) const goodResult = new AsyncResult(Ok(1)) await badResult.orElse(() => Ok(123)).promise // Ok(123) await goodResult.orElse(() => Ok(123)).promise // Ok(1) ``` ``` -------------------------------- ### Construct AsyncOption Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Create an AsyncOption directly from an Option or a Promise resolving to an Option. ```typescript const option1 = new AsyncOption(Some(1)) const option2 = new AsyncOption((async () => None)()) ``` -------------------------------- ### unwrapOrElse() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the contained Ok value or computes a value using a provided function if the Result is an Err. ```APIDOC ## `unwrapOrElse()` ```typescript unwrapOrElse(f: (error: E) => T2): T | T2 ``` Returns the contained `Ok` value or computes a value with a provided function. The function is called at most one time, only if needed. Example: ```typescript Ok('OK').unwrapOrElse( (error) => { console.log(`Called, got ${error}`); return 'UGH'; } ) // => 'OK', nothing printed Err('A03B').unwrapOrElse((error) => `UGH, got ${error}`) // => 'UGH, got A03B' ``` ``` -------------------------------- ### Err.EMPTY Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md A static Err instance containing undefined. Useful for representing a failure without a specific error value. ```APIDOC ## Err.EMPTY ### Description A static `Err` instance containing `undefined`. Useful when you need to represent a failure without a meaningful error value. ### Method `static readonly EMPTY: Err` ### Request Example ```typescript const x: Result = Err.EMPTY ``` ### Response #### Success Response - **EMPTY**: Err - A predefined Err instance with an undefined value. ### Response Example ```typescript // Err(undefined) ``` ``` -------------------------------- ### Unwrap Ok Value with unwrap Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the contained Ok value. Throws an error if the Result is Err. Use with caution, preferring explicit error handling. ```typescript unwrap(): T ``` ```typescript let goodResult = new Ok(1); let badResult = new Err(new Error('something went wrong')); goodResult.unwrap(); // 1 badResult.unwrap(); // throws Error("something went wrong") ``` -------------------------------- ### Return Other Result with or Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Returns the current Result if it is Ok, otherwise returns the provided `other` Result. The `other` Result is evaluated eagerly. ```typescript or(other: Result): Result ``` ```typescript Ok(1).or(Ok(2)) // => Ok(1) Err('error here').or(Ok(2)) // => Ok(2) ``` -------------------------------- ### Convert Option to AsyncOption Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Use the Option.toAsyncOption() method to convert a synchronous Option to an AsyncOption. ```typescript const option3 = Some(1).toAsyncOption() ``` -------------------------------- ### Option `expect` Method Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/option.md Returns the contained Some value or throws an error with a provided message if the Option is None. Prefer `value` if no exception is expected. ```typescript expect(msg: string): T ``` -------------------------------- ### Map Ok Value or Use Default Function with mapOrElse Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/result.md Converts the Ok value using a mapper function or produces a default value by calling a function if the Result is Err. The default function is evaluated lazily. ```typescript mapOrElse(default_: (error: E) => U, mapper: (val: T) => U): U ``` ```typescript let goodResult = Ok(1); let badResult = Err(new Error('something went wrong')); goodResult.mapOrElse((_error) => 0, (value) => -value) // -1 badResult.mapOrElse((_error) => 0, (value) => -value) // 0 ``` -------------------------------- ### map() Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncoption.md Maps an AsyncOption to AsyncOption by applying a function to a contained Some value, leaving a None value untouched. Useful for composing asynchronous operations. ```APIDOC ## `map()` ```typescript map(mapper: (val: T) => U | Promise): AsyncOption ``` Maps an `AsyncOption` to `AsyncOption` by applying a function to a contained `Some` value, leaving a `None` value untouched. This function can be used to compose the results of two functions. Example: ```typescript let hasValue = Some(1).toAsyncOption() let noValue = None.toAsyncOption() await hasValue.map(async (value) => value * 2).promise // Some(2) await noValue.map(async (value) => value * 2).promise // None ``` ``` -------------------------------- ### promise Attribute Source: https://github.com/lune-climate/ts-results-es/blob/master/docs/reference/asyncresult.md Provides a Promise that resolves to a synchronous Result, allowing conversion of AsyncResult to Result. ```APIDOC ## `promise` ```typescript promise: Promise> ``` ### Description A promise that resolves to a synchronous result. You can await it to convert `AsyncResult` to `Result`, but prefer awaiting `AsyncResult` directly (see: [then()]()). Only use this property if you need the underlying Promise for specific use cases. ```