@carbonteq/fp 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/flow-experimental.cjs +286 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- package/dist/result-experimental.cjs +1266 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- package/examples/README.md +46 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +237 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +241 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +50 -18
package/dist/result.d.cts
CHANGED
|
@@ -2,15 +2,18 @@ import { UNIT } from "./unit.cjs";
|
|
|
2
2
|
import { Option } from "./option.cjs";
|
|
3
3
|
|
|
4
4
|
//#region src/result.d.ts
|
|
5
|
-
type Mapper<T, U
|
|
6
|
-
type FlatZipInput<_T, U
|
|
7
|
-
|
|
5
|
+
type Mapper<T, U> = (val: T) => U;
|
|
6
|
+
type FlatZipInput<_T, U, E> = Result<U, E> | Result<Promise<U>, E> | Promise<Result<U, E>> | Promise<Result<Promise<U>, E>>;
|
|
7
|
+
/** Result alias for success-without-payload operations. */
|
|
8
|
+
type UnitResult<E = never> = Result<UNIT, E>;
|
|
9
|
+
/** Extracts `{ ok, err }` branch types from a Result type. */
|
|
8
10
|
type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
|
|
9
11
|
ok: U;
|
|
10
12
|
err: E;
|
|
11
13
|
} : never;
|
|
12
14
|
type CombinedResultOk<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["ok"] };
|
|
13
15
|
type CombinedResultErr<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["err"] }[number];
|
|
16
|
+
/** Combines a tuple of Results into one Result of tuple values. */
|
|
14
17
|
type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
|
|
15
18
|
type UnwrapPromises<T extends Result<unknown, unknown>[]> = { [K in keyof T]: Awaited<UnwrapResult<T[K]>["ok"]> };
|
|
16
19
|
type IsPromise<T> = T extends Promise<unknown> ? true : false;
|
|
@@ -20,122 +23,810 @@ declare const NO_ERR: unique symbol;
|
|
|
20
23
|
/** Internal symbol for accessing private factory - not exported */
|
|
21
24
|
declare const RESULT_INTERNAL: unique symbol;
|
|
22
25
|
type NO_ERR = typeof NO_ERR;
|
|
23
|
-
type ResultCtx<E
|
|
24
|
-
asyncErr: E
|
|
26
|
+
type ResultCtx<E> = {
|
|
27
|
+
asyncErr: E | NO_ERR;
|
|
25
28
|
};
|
|
26
|
-
interface MatchCases<T, E
|
|
27
|
-
Ok: (val: T) => U
|
|
28
|
-
Err: (err: E
|
|
29
|
+
interface MatchCases<T, E, U> {
|
|
30
|
+
Ok: (val: T) => U;
|
|
31
|
+
Err: (err: E) => U;
|
|
29
32
|
}
|
|
30
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Wrapper that makes Result yieldable with proper type tracking.
|
|
35
|
+
* The Generator signature ensures TypeScript tracks the inner type T.
|
|
36
|
+
*
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
declare class ResultYieldWrap<T, E> {
|
|
40
|
+
readonly result: Result<T, E>;
|
|
41
|
+
constructor(result: Result<T, E>);
|
|
42
|
+
[Symbol.iterator](): Generator<ResultYieldWrap<T, E>, T, unknown>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Wrapper that makes Result yieldable in async generators with proper type tracking.
|
|
46
|
+
* Supports Promise<Result<T, E>> for async result chaining.
|
|
47
|
+
*
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
declare class AsyncResultYieldWrap<T, E> {
|
|
51
|
+
readonly result: Promise<Result<T, E>>;
|
|
52
|
+
constructor(result: Promise<Result<T, E>>);
|
|
53
|
+
[Symbol.asyncIterator](): AsyncGenerator<AsyncResultYieldWrap<T, E>, T, unknown>;
|
|
54
|
+
}
|
|
55
|
+
/** Extract error type from yielded values */
|
|
56
|
+
type ExtractResultError<T> = T extends ResultYieldWrap<any, infer E> ? E : never;
|
|
57
|
+
/** Extract error type from async yielded values */
|
|
58
|
+
type ExtractAsyncResultError<T> = T extends AsyncResultYieldWrap<any, infer E> ? E : never;
|
|
59
|
+
/** Extract error type directly from Result */
|
|
60
|
+
type ExtractError<T> = T extends Result<any, infer E> ? E : never;
|
|
61
|
+
/**
|
|
62
|
+
* Represents a computation that can succeed (`Ok<T>`) or fail (`Err<E>`).
|
|
63
|
+
* Provides composable transformations with explicit error propagation.
|
|
64
|
+
*/
|
|
65
|
+
declare class Result<T, E> {
|
|
31
66
|
#private;
|
|
32
67
|
/** Discriminant tag for type-level identification */
|
|
33
68
|
readonly _tag: "Ok" | "Err";
|
|
34
69
|
private constructor();
|
|
35
70
|
/** Internal factory for namespace functions - not part of public API */
|
|
36
71
|
static [RESULT_INTERNAL]: {
|
|
37
|
-
create<T_1, E_1>(val: T_1, err: E_1, ctx: ResultCtx<E_1>, tag: "
|
|
72
|
+
create<T_1, E_1>(val: T_1, err: E_1, ctx: ResultCtx<E_1>, tag: "Err" | "Ok"): Result<T_1, E_1>;
|
|
38
73
|
};
|
|
39
74
|
/** Get the actual error value (from async context or sync field) */
|
|
40
75
|
private getErr;
|
|
41
76
|
/** Singleton UNIT_RESULT for void-success operations */
|
|
42
77
|
static readonly UNIT_RESULT: Result<UNIT, never>;
|
|
43
|
-
/**
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
78
|
+
/**
|
|
79
|
+
* Creates an Ok containing the given value.
|
|
80
|
+
*
|
|
81
|
+
* @template T - Success value type
|
|
82
|
+
* @template E - Error type (defaults to never)
|
|
83
|
+
* @param val - Success value
|
|
84
|
+
* @returns Result in the Ok state
|
|
85
|
+
*/
|
|
86
|
+
static Ok<T, E = never>(this: void, val: T): Result<T, E>;
|
|
87
|
+
/**
|
|
88
|
+
* Creates an Err containing the given error.
|
|
89
|
+
*
|
|
90
|
+
* @template E - Error type
|
|
91
|
+
* @template T - Success value type (defaults to never)
|
|
92
|
+
* @param err - Error value
|
|
93
|
+
* @returns Result in the Err state
|
|
94
|
+
*/
|
|
95
|
+
static Err<E, T = never>(this: void, err: E): Result<T, E>;
|
|
96
|
+
/**
|
|
97
|
+
* Type guard for Ok state.
|
|
98
|
+
*
|
|
99
|
+
* @returns true if this Result is Ok
|
|
100
|
+
*/
|
|
48
101
|
isOk(): this is Result<T, never>;
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Type guard for Err state.
|
|
104
|
+
*
|
|
105
|
+
* @returns true if this Result is Err
|
|
106
|
+
*/
|
|
107
|
+
isErr(): this is Result<never, E>;
|
|
108
|
+
/**
|
|
109
|
+
* Type guard for Ok containing UNIT.
|
|
110
|
+
*
|
|
111
|
+
* @returns true if the Ok value is UNIT
|
|
112
|
+
*/
|
|
52
113
|
isUnit(): this is Result<UNIT, never>;
|
|
114
|
+
/**
|
|
115
|
+
* Returns a string representation of the Result.
|
|
116
|
+
*
|
|
117
|
+
* @returns "Result::Ok<value>" or "Result::Err<error>"
|
|
118
|
+
*/
|
|
53
119
|
toString(): string;
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
120
|
+
/**
|
|
121
|
+
* Returns the contained value or throws.
|
|
122
|
+
*
|
|
123
|
+
* If Err and the error is an Error, re-throws it; otherwise throws
|
|
124
|
+
* UnwrappedOkWithErr. For async values, returns a Promise that rejects
|
|
125
|
+
* on error.
|
|
126
|
+
*
|
|
127
|
+
* @returns The contained value (sync or async)
|
|
128
|
+
* @throws Error or UnwrappedOkWithErr when Err
|
|
129
|
+
*/
|
|
130
|
+
unwrap(this: Result<Promise<T>, E>): Promise<T>;
|
|
131
|
+
unwrap(this: Result<T, E>): T;
|
|
132
|
+
/**
|
|
133
|
+
* Returns the contained error or throws.
|
|
134
|
+
*
|
|
135
|
+
* For async values, returns a Promise resolving to the error or rejecting
|
|
136
|
+
* with UnwrappedErrWithOk when Ok.
|
|
137
|
+
*
|
|
138
|
+
* @returns The contained error (sync or async)
|
|
139
|
+
* @throws UnwrappedErrWithOk when called on Ok
|
|
140
|
+
*/
|
|
141
|
+
unwrapErr<T, E>(this: Result<T, E>): E;
|
|
142
|
+
unwrapErr<T, E>(this: Result<Promise<T>, E>): Promise<E>;
|
|
143
|
+
/**
|
|
144
|
+
* Returns the contained value or the provided default.
|
|
145
|
+
*
|
|
146
|
+
* For async values, returns a Promise resolving to the value or default.
|
|
147
|
+
*
|
|
148
|
+
* @param defaultValue - Fallback value when Err
|
|
149
|
+
* @returns The contained value or default (sync or async)
|
|
150
|
+
*/
|
|
151
|
+
unwrapOr<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, defaultValue: Curr): Promise<Curr>;
|
|
152
|
+
unwrapOr(this: Result<T, E>, defaultValue: T): T;
|
|
153
|
+
/**
|
|
154
|
+
* Returns the contained value or computes a default from the error.
|
|
155
|
+
*
|
|
156
|
+
* For async values, returns a Promise resolving to the value or computed
|
|
157
|
+
* default.
|
|
158
|
+
*
|
|
159
|
+
* @param fn - Function that maps the error to a fallback value
|
|
160
|
+
* @returns The contained value or computed default (sync or async)
|
|
161
|
+
*/
|
|
162
|
+
unwrapOrElse<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, fn: (err: E) => Curr): Promise<Curr>;
|
|
163
|
+
unwrapOrElse(this: Result<T, E>, fn: (err: E) => T): T;
|
|
164
|
+
/**
|
|
165
|
+
* Safely unwraps the value, returning null for Err.
|
|
166
|
+
*
|
|
167
|
+
* For async values, returns a Promise resolving to the value or null.
|
|
168
|
+
*
|
|
169
|
+
* @returns The contained value or null (sync or async)
|
|
170
|
+
*/
|
|
171
|
+
safeUnwrap(this: Result<never, E>): null;
|
|
172
|
+
safeUnwrap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>): Promise<Curr | null> | null;
|
|
173
|
+
safeUnwrap(this: Result<T, E>): T | null;
|
|
174
|
+
/**
|
|
175
|
+
* Exhaustive pattern match on Result state.
|
|
176
|
+
*
|
|
177
|
+
* @template U - Result type of the handlers
|
|
178
|
+
* @param cases - Handlers for Ok and Err
|
|
179
|
+
* @returns Result of the matching handler
|
|
180
|
+
*/
|
|
181
|
+
match<U>(cases: MatchCases<T, E, U>): U;
|
|
182
|
+
/**
|
|
183
|
+
* Transforms the success value using the provided function.
|
|
184
|
+
*
|
|
185
|
+
* If the Result is Ok, applies the function to the value and wraps the result
|
|
186
|
+
* in a new Ok. If Err, propagates the error unchanged without calling the function.
|
|
187
|
+
*
|
|
188
|
+
* @param fn - Function to transform the success value
|
|
189
|
+
* @returns Result<U, E> with transformed value or propagated error
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* ```ts
|
|
193
|
+
* Result.Ok(42).map((x) => x * 2); // Ok(84)
|
|
194
|
+
* Result.Err("fail").map((x) => x * 2); // Err("fail")
|
|
195
|
+
* ```
|
|
196
|
+
*
|
|
197
|
+
* @see flatMap
|
|
198
|
+
*/
|
|
199
|
+
map<T, U, E>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<U>): Result<Promise<U>, E>;
|
|
200
|
+
map<T, U, E>(this: Result<Promise<T>, E>, fn: (val: T) => U): Result<Promise<U>, E>;
|
|
201
|
+
map<In, U>(this: Result<In, E>, fn: (val: In) => Promise<U>): Result<Promise<U>, E>;
|
|
202
|
+
map<In, U>(this: Result<In, E>, fn: (val: In) => U): Result<U, E>;
|
|
203
|
+
/**
|
|
204
|
+
* Safely maps a promised Ok value while propagating async errors.
|
|
205
|
+
*
|
|
206
|
+
* @template In - Input value type
|
|
207
|
+
* @template U - Output value type
|
|
208
|
+
* @template E - Error type
|
|
209
|
+
* @param p - Promise of Ok value or ERR sentinel
|
|
210
|
+
* @param mapper - Transform function
|
|
211
|
+
* @param ctx - New async context to populate on error
|
|
212
|
+
* @param parentCtx - Parent async context to read error from
|
|
213
|
+
* @returns Promise of transformed value or ERR sentinel
|
|
214
|
+
*/
|
|
76
215
|
private static safeMap;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Transforms the error value while preserving the success value.
|
|
218
|
+
*
|
|
219
|
+
* If the Result is Err, applies the function to the error. If Ok, returns
|
|
220
|
+
* the Ok unchanged without calling the function.
|
|
221
|
+
*
|
|
222
|
+
* @param fn - Function to transform the error
|
|
223
|
+
* @returns Result<T, E2> with transformed error or original Ok
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```ts
|
|
227
|
+
* Result.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
|
|
228
|
+
* Result.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
|
|
229
|
+
*
|
|
230
|
+
* // Add context to errors
|
|
231
|
+
* fetchData()
|
|
232
|
+
* .mapErr((e) => new ContextualError("Failed to fetch data", e));
|
|
233
|
+
* ```
|
|
234
|
+
*
|
|
235
|
+
* @see mapBoth
|
|
236
|
+
*/
|
|
237
|
+
mapErr<U>(fn: Mapper<E, U>): Result<T, U>;
|
|
238
|
+
/**
|
|
239
|
+
* Transforms both the Ok and Err values.
|
|
240
|
+
*
|
|
241
|
+
* Applies fnOk when Ok and fnErr when Err. Supports async Ok values via
|
|
242
|
+
* overloads; returns Result with mapped types.
|
|
243
|
+
*
|
|
244
|
+
* @param fnOk - Mapper for Ok values
|
|
245
|
+
* @param fnErr - Mapper for Err values
|
|
246
|
+
* @returns Result with both branches transformed
|
|
247
|
+
*/
|
|
248
|
+
mapBoth<T2, E2, In = Awaited<T>>(this: Result<Promise<In>, E>, fnOk: (val: In) => T2 | Promise<T2>, fnErr: (val: E) => E2): Result<Promise<T2>, E2>;
|
|
249
|
+
mapBoth<T2, E2>(this: Result<T, E>, fnOk: (val: T) => Promise<T2>, fnErr: (val: E) => E2): Result<Promise<T2>, E2>;
|
|
250
|
+
mapBoth<T2, E2>(this: Result<T, E>, fnOk: (val: T) => T2, fnErr: (val: E) => E2): Result<T2, E2>;
|
|
251
|
+
/**
|
|
252
|
+
* Chains operations that return Results, flattening nested Results.
|
|
253
|
+
*
|
|
254
|
+
* If the Result is Ok, applies the function (which returns a new Result) and
|
|
255
|
+
* returns that Result directly. If Err, propagates the error unchanged.
|
|
256
|
+
*
|
|
257
|
+
* Error types are unified: `Result<U, E | E2>`.
|
|
258
|
+
*
|
|
259
|
+
* @param fn - Function that returns a Result
|
|
260
|
+
* @returns Result<U, E | E2> from the function or propagated error
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* ```ts
|
|
264
|
+
* // Success chain
|
|
265
|
+
* Result.Ok(42)
|
|
266
|
+
* .flatMap((x) => Result.Ok(x + 1)) // Ok(43)
|
|
267
|
+
* .flatMap((x) => Result.Err("too big")); // Err("too big")
|
|
268
|
+
*
|
|
269
|
+
* // Error propagation
|
|
270
|
+
* Result.Err("initial").flatMap((x) => Result.Ok(x + 1)); // Err("initial")
|
|
271
|
+
* ```
|
|
272
|
+
*
|
|
273
|
+
* @see map
|
|
274
|
+
* @see flatZip
|
|
275
|
+
*/
|
|
276
|
+
flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Result<Promise<U>, E2>): Result<Promise<U>, E | E2>;
|
|
277
|
+
flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<Promise<U>, E2>>): Result<Promise<U>, E | E2>;
|
|
278
|
+
flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<U, E2>>): Result<Promise<U>, E | E2>;
|
|
279
|
+
flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Result<U, E | E2>): Result<Promise<U>, E | E2>;
|
|
280
|
+
flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<Promise<U>, E | E2>>): Result<Promise<U>, E | E2>;
|
|
281
|
+
flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<U, E | E2>>): Result<Promise<U>, E | E2>;
|
|
282
|
+
flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Result<U, E2>): Result<U, E | E2>;
|
|
283
|
+
flatMap<T, _U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E2>>): never;
|
|
284
|
+
flatMap<T, _U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E | E2>>): never;
|
|
285
|
+
/**
|
|
286
|
+
* Normalizes sync/async flatMap outputs to a value or Promise.
|
|
287
|
+
*
|
|
288
|
+
* @template U - Success value type
|
|
289
|
+
* @template E - Original error type
|
|
290
|
+
* @template E2 - Mapped error type
|
|
291
|
+
* @template T - Input value type
|
|
292
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
293
|
+
* @param mapped - FlatMap output (sync or async Result)
|
|
294
|
+
* @returns Value, Promise, or ERR sentinel
|
|
295
|
+
*/
|
|
90
296
|
private static flatMapHelper;
|
|
297
|
+
/**
|
|
298
|
+
* Extracts the inner value from a Result, updating error context on failure.
|
|
299
|
+
*
|
|
300
|
+
* @template U - Success value type
|
|
301
|
+
* @template E - Original error type
|
|
302
|
+
* @template E2 - Mapped error type
|
|
303
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
304
|
+
* @param r - Inner Result to unwrap
|
|
305
|
+
* @returns Value, Promise, or ERR sentinel
|
|
306
|
+
*/
|
|
91
307
|
private static flatMapInnerHelper;
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
308
|
+
/**
|
|
309
|
+
* Pairs the original value with a derived value in a tuple.
|
|
310
|
+
*
|
|
311
|
+
* Unlike `map` which replaces the value, `zip` keeps the original and adds
|
|
312
|
+
* the derived value, creating `[original, derived]`.
|
|
313
|
+
*
|
|
314
|
+
* @param fn - Function to derive a value from the original
|
|
315
|
+
* @returns Result<[T, U], E> containing tuple of original and derived values
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* ```ts
|
|
319
|
+
* Result.Ok(42).zip((x) => x * 10); // Ok([42, 420])
|
|
320
|
+
* Result.Err("fail").zip((x) => x * 10); // Err("fail")
|
|
321
|
+
*
|
|
322
|
+
* // Keep original while computing related value
|
|
323
|
+
* Result.Ok(user).zip((u) => u.permissions.length); // Ok([user, 5])
|
|
324
|
+
* ```
|
|
325
|
+
*
|
|
326
|
+
* @see flatZip
|
|
327
|
+
* @see map
|
|
328
|
+
*/
|
|
329
|
+
zip<T, U, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => Promise<U>): Result<Promise<[In, U]>, E>;
|
|
330
|
+
zip<T, U, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => U): Result<Promise<[In, U]>, E>;
|
|
331
|
+
zip<T, U>(this: Result<T, E>, fn: (val: T) => Promise<U>): Result<Promise<[T, U]>, E>;
|
|
332
|
+
zip<T, U>(this: Result<T, E>, fn: (val: T) => U): Result<[T, U], E>;
|
|
333
|
+
/**
|
|
334
|
+
* Combines the current Result with another independent Result in a tuple.
|
|
335
|
+
*
|
|
336
|
+
* Unlike `zip` which derives a value from the original, `flatZip` works with
|
|
337
|
+
* two independent Results. If either is Err, propagates the first error.
|
|
338
|
+
*
|
|
339
|
+
* Supports both sync and async Results. Async combinations return
|
|
340
|
+
* `Result<Promise<[T, U]>, E | E2>`.
|
|
341
|
+
*
|
|
342
|
+
* @param fn - Function that receives the value and returns another Result
|
|
343
|
+
* @returns Result<[T, U], E | E2> containing tuple of both values, or error
|
|
344
|
+
*
|
|
345
|
+
* @example
|
|
346
|
+
* ```ts
|
|
347
|
+
* Result.Ok(42)
|
|
348
|
+
* .flatZip((x) => Result.Ok(x + 5)) // Ok([42, 47])
|
|
349
|
+
* .flatZip(([a, b]) => Result.Err("x")); // Err("x")
|
|
350
|
+
*
|
|
351
|
+
* Result.Ok(42).flatZip((x) => Result.Err("fail")); // Err("fail")
|
|
352
|
+
* Result.Err("init").flatZip((x) => Result.Ok(5)); // Err("init")
|
|
353
|
+
* ```
|
|
354
|
+
*
|
|
355
|
+
* @see zip
|
|
356
|
+
* @see flatMap
|
|
357
|
+
*/
|
|
358
|
+
flatZip<U, E2, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => FlatZipInput<In, U, E | E2>): Result<Promise<[In, Awaited<U>]>, E | E2>;
|
|
359
|
+
flatZip<U, E2, In = Awaited<T>>(this: Result<In, E>, fn: (val: In) => Promise<Result<U, E2>> | Promise<Result<Promise<U>, E2>> | Result<Promise<U>, E2>): Result<Promise<[In, Awaited<U>]>, E | E2>;
|
|
360
|
+
flatZip<U, E2, In = Awaited<T>>(this: Result<In, E>, fn: (val: In) => Result<U, E2>): Result<[In, U], E | E2>;
|
|
361
|
+
/**
|
|
362
|
+
* Normalizes sync/async flatZip outputs to a tuple or ERR sentinel.
|
|
363
|
+
*
|
|
364
|
+
* @template U - Derived value type
|
|
365
|
+
* @template E - Original error type
|
|
366
|
+
* @template E2 - Mapped error type
|
|
367
|
+
* @template In - Original value type
|
|
368
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
369
|
+
* @param originalVal - Original value to preserve
|
|
370
|
+
* @param mapped - FlatZip output (sync or async Result)
|
|
371
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
372
|
+
*/
|
|
99
373
|
private static flatZipHelper;
|
|
374
|
+
/**
|
|
375
|
+
* Extracts the inner value for flatZip, updating error context on failure.
|
|
376
|
+
*
|
|
377
|
+
* @template U - Derived value type
|
|
378
|
+
* @template E - Original error type
|
|
379
|
+
* @template E2 - Mapped error type
|
|
380
|
+
* @template In - Original value type
|
|
381
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
382
|
+
* @param originalVal - Original value to preserve
|
|
383
|
+
* @param r - Inner Result to unwrap
|
|
384
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
385
|
+
*/
|
|
100
386
|
private static flatZipInnerHelper;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
387
|
+
/**
|
|
388
|
+
* Runs a Result-producing function and turns Ok into Err on failure.
|
|
389
|
+
*
|
|
390
|
+
* If this Result is Ok, calls fn with the value. If fn returns Err, the
|
|
391
|
+
* resulting Result becomes Err while the original Ok value is preserved
|
|
392
|
+
* when fn succeeds.
|
|
393
|
+
*
|
|
394
|
+
* @template E2 - Additional error type
|
|
395
|
+
* @param fn - Function producing a Result
|
|
396
|
+
* @returns Result with original value or combined error
|
|
397
|
+
*/
|
|
398
|
+
zipErr<E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E | E2>;
|
|
399
|
+
zipErr<E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E | E2>;
|
|
400
|
+
zipErr<E2>(this: Result<T, E>, fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;
|
|
401
|
+
/**
|
|
402
|
+
* Tracks errors from a Result while preserving the original value.
|
|
403
|
+
*
|
|
404
|
+
* @template In - Original value type
|
|
405
|
+
* @template E - Error type
|
|
406
|
+
* @param v - Original value to preserve
|
|
407
|
+
* @param r - Result to inspect for errors
|
|
408
|
+
* @param newCtx - Context to populate on error
|
|
409
|
+
* @returns Original value or Promise of value
|
|
410
|
+
*/
|
|
104
411
|
private static zipErrHelper;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
412
|
+
private static captureZipErr;
|
|
413
|
+
/**
|
|
414
|
+
* Runs multiple validators on the Ok value, collecting ALL errors.
|
|
415
|
+
*
|
|
416
|
+
* Unlike most Result methods which short-circuit on the first error,
|
|
417
|
+
* `validate` runs ALL validators and collects all errors together.
|
|
418
|
+
* This is useful for form validation where you want to show all errors at once.
|
|
419
|
+
*
|
|
420
|
+
* If the Result is Err, returns it unchanged without running validators.
|
|
421
|
+
*
|
|
422
|
+
* Supports both sync and async validators. If any validator is async,
|
|
423
|
+
* returns `Result<Promise<T>, E | VE[]>`.
|
|
424
|
+
*
|
|
425
|
+
* @param validators - Array of validator functions that return Result
|
|
426
|
+
* @returns Result<T, E | VE[]> with original value or array of all errors
|
|
427
|
+
*
|
|
428
|
+
* @example
|
|
429
|
+
* ```ts
|
|
430
|
+
* const validators = [
|
|
431
|
+
* (x: number) => x > 0 ? Result.Ok(true) : Result.Err("must be positive"),
|
|
432
|
+
* (x: number) => x < 100 ? Result.Ok(true) : Result.Err("must be < 100"),
|
|
433
|
+
* (x: number) => x % 2 === 0 ? Result.Ok(true) : Result.Err("must be even"),
|
|
434
|
+
* ];
|
|
435
|
+
*
|
|
436
|
+
* Result.Ok(42).validate(validators); // Ok(42)
|
|
437
|
+
* Result.Ok(101).validate(validators); // Err(["must be < 100"])
|
|
438
|
+
* Result.Ok(-5).validate(validators); // Err(["must be positive", "must be even"])
|
|
439
|
+
* Result.Err("init").validate(validators); // Err("init") - validators not run
|
|
440
|
+
*
|
|
441
|
+
* // With async validators (returns Result<Promise<T>, ...>)
|
|
442
|
+
* await Result.Ok(data).validate([
|
|
443
|
+
* async (d) => await validateEmail(d),
|
|
444
|
+
* async (d) => await validatePhone(d),
|
|
445
|
+
* ]);
|
|
446
|
+
* ```
|
|
447
|
+
*
|
|
448
|
+
* @see all
|
|
449
|
+
*/
|
|
450
|
+
validate<VE extends unknown[]>(this: Result<T, E>, validators: { [K in keyof VE]: (val: T) => Result<unknown, VE[K]> }): Result<T, E | VE[number][]>;
|
|
451
|
+
validate<VE extends unknown[]>(this: Result<T, E>, validators: { [K in keyof VE]: (val: T) => Promise<Result<unknown, VE[K]>> }): Result<Promise<T>, E | VE[number][]>;
|
|
452
|
+
validate<VE extends unknown[], In = Awaited<T>>(this: Result<T, E> | Result<Promise<T>, E>, validators: { [K in keyof VE]: (val: In) => Promise<Result<unknown, VE[K]>> | Result<unknown, VE[K]> }): Result<Promise<T>, E | VE[number][]>;
|
|
453
|
+
/**
|
|
454
|
+
* Collapses validator Results into a single value or ERR sentinel.
|
|
455
|
+
*
|
|
456
|
+
* @template Val - Success value type
|
|
457
|
+
* @template Err - Error type
|
|
458
|
+
* @param results - Validator Results to combine
|
|
459
|
+
* @param currCtx - Context to populate on error
|
|
460
|
+
* @param currVal - Original value to return on success
|
|
461
|
+
* @returns Original value, Promise of value, or ERR sentinel
|
|
462
|
+
*/
|
|
108
463
|
private static validateHelper;
|
|
464
|
+
/**
|
|
465
|
+
* Combines multiple Results, collecting all values or all errors.
|
|
466
|
+
*
|
|
467
|
+
* Unlike typical Result behavior which short-circuits on first error,
|
|
468
|
+
* `all` collects ALL errors from all Results. This is useful when you
|
|
469
|
+
* want to show complete validation feedback.
|
|
470
|
+
*
|
|
471
|
+
* - All Ok → `Ok([...values])` with preserved tuple types
|
|
472
|
+
* - Any Err → `Err([...errors])` collecting ALL errors
|
|
473
|
+
*
|
|
474
|
+
* @param results - Variable number of Results to combine
|
|
475
|
+
* @returns Result with tuple of all values, or array of all errors
|
|
476
|
+
*
|
|
477
|
+
* @example
|
|
478
|
+
* ```ts
|
|
479
|
+
* Result.all(Result.Ok(1), Result.Ok(2), Result.Ok(3)); // Ok([1, 2, 3])
|
|
480
|
+
* Result.all(Result.Ok(1), Result.Err("a"), Result.Err("b")); // Err(["a", "b"])
|
|
481
|
+
* Result.all(); // Ok([])
|
|
482
|
+
*
|
|
483
|
+
* // Real-world: Parallel validation
|
|
484
|
+
* const [user, posts, likes] = await Promise.all([
|
|
485
|
+
* fetchUser(id),
|
|
486
|
+
* fetchPosts(id),
|
|
487
|
+
* fetchLikes(id),
|
|
488
|
+
* ]);
|
|
489
|
+
*
|
|
490
|
+
* const combined = Result.all(user, posts, likes);
|
|
491
|
+
* // Ok([User, Post[], Like[]]) or Err([...errors])
|
|
492
|
+
* ```
|
|
493
|
+
*
|
|
494
|
+
* @see any
|
|
495
|
+
* @see validate
|
|
496
|
+
*/
|
|
109
497
|
static all<T extends Result<unknown, unknown>[]>(...results: T): HasPromise<T> extends true ? Result<Promise<UnwrapPromises<T>>, CombinedResultErr<T>[]> : Result<CombinedResultOk<T>, CombinedResultErr<T>[]>;
|
|
110
|
-
/**
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
498
|
+
/**
|
|
499
|
+
* Returns the first Ok, or collects all errors if all are Err.
|
|
500
|
+
*
|
|
501
|
+
* Useful for fallback chains where you want the first success, but want
|
|
502
|
+
* to collect all errors if everything fails.
|
|
503
|
+
*
|
|
504
|
+
* - First Ok → Returns that Ok immediately
|
|
505
|
+
* - All Err → `Err([...all errors])`
|
|
506
|
+
*
|
|
507
|
+
* For async Ok values, this waits for settlement and selects the first
|
|
508
|
+
* successful candidate in input order (not fastest-to-resolve order).
|
|
509
|
+
*
|
|
510
|
+
* @param results - Variable number of Results to check
|
|
511
|
+
* @returns First Ok found, or Err with array of all errors
|
|
512
|
+
*
|
|
513
|
+
* @example
|
|
514
|
+
* ```ts
|
|
515
|
+
* Result.any(
|
|
516
|
+
* Result.Err("Error 1"),
|
|
517
|
+
* Result.Ok("First success"),
|
|
518
|
+
* Result.Ok("Second success"),
|
|
519
|
+
* ); // Ok("First success")
|
|
520
|
+
*
|
|
521
|
+
* Result.any(
|
|
522
|
+
* Result.Err("Error 1"),
|
|
523
|
+
* Result.Err("Error 2"),
|
|
524
|
+
* Result.Err("Error 3"),
|
|
525
|
+
* ); // Err(["Error 1", "Error 2", "Error 3"])
|
|
526
|
+
*
|
|
527
|
+
* // Fallback chain
|
|
528
|
+
* Result.any(
|
|
529
|
+
* fetchFromCache(key),
|
|
530
|
+
* fetchFromDb(key),
|
|
531
|
+
* fetchFromRemote(key),
|
|
532
|
+
* );
|
|
533
|
+
* ```
|
|
534
|
+
*
|
|
535
|
+
* @see all
|
|
536
|
+
*/
|
|
537
|
+
static any<U, F>(...results: Result<U, F>[]): Result<U, F[]>;
|
|
538
|
+
/**
|
|
539
|
+
* Executes a side effect function for Ok values, then returns self.
|
|
540
|
+
*
|
|
541
|
+
* Useful for logging, debugging, or executing effects without breaking the
|
|
542
|
+
* method chain. The function is only called if the Result is Ok.
|
|
543
|
+
*
|
|
544
|
+
* @param fn - Function to execute with the Ok value
|
|
545
|
+
* @returns The same Result (chainable)
|
|
546
|
+
*
|
|
547
|
+
* @example
|
|
548
|
+
* ```ts
|
|
549
|
+
* Result.Ok(42)
|
|
550
|
+
* .tap((x) => console.log(`Processing: ${x}`))
|
|
551
|
+
* .map((x) => x * 2);
|
|
552
|
+
* // Logs: "Processing: 42"
|
|
553
|
+
* // Returns: Ok(84)
|
|
554
|
+
*
|
|
555
|
+
* // Err - tap does nothing
|
|
556
|
+
* Result.Err("fail").tap((x) => console.log(x)); // Err("fail")
|
|
557
|
+
* ```
|
|
558
|
+
*
|
|
559
|
+
* @see tapErr
|
|
560
|
+
*/
|
|
561
|
+
tap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, fn: (val: Curr) => void): Result<Promise<Curr>, E>;
|
|
562
|
+
tap(this: Result<T, E>, fn: (val: T) => void): Result<T, E>;
|
|
563
|
+
/**
|
|
564
|
+
* Executes a side effect function for Err values, then returns self.
|
|
565
|
+
*
|
|
566
|
+
* Useful for logging errors or executing cleanup without breaking the chain.
|
|
567
|
+
* The function is only called if the Result is Err.
|
|
568
|
+
*
|
|
569
|
+
* @param fn - Function to execute with the error (sync or async)
|
|
570
|
+
* @returns The same Result (chainable)
|
|
571
|
+
*
|
|
572
|
+
* @example
|
|
573
|
+
* ```ts
|
|
574
|
+
* Result.Err("Connection failed")
|
|
575
|
+
* .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
|
|
576
|
+
* .orElse((e) => Result.Ok(defaultValue));
|
|
577
|
+
* // Logs error timestamp
|
|
578
|
+
* // Returns: Ok(defaultValue)
|
|
579
|
+
*
|
|
580
|
+
* // Ok - tapErr does nothing
|
|
581
|
+
* Result.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
|
|
582
|
+
* ```
|
|
583
|
+
*
|
|
584
|
+
* @see tap
|
|
585
|
+
*/
|
|
586
|
+
tapErr(fn: (err: E) => void): Result<T, E>;
|
|
587
|
+
/**
|
|
588
|
+
* Swaps the Ok and Err states, turning success into failure and vice versa.
|
|
589
|
+
*
|
|
590
|
+
* Useful for inverting the meaning of a Result, such as converting
|
|
591
|
+
* validation errors to successes and valid values to errors.
|
|
592
|
+
*
|
|
593
|
+
* @returns Result<E, T> with swapped states
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ```ts
|
|
597
|
+
* Result.Ok("Success value").flip(); // Err("Success value")
|
|
598
|
+
* Result.Err("Error value").flip(); // Ok("Error value")
|
|
599
|
+
*
|
|
600
|
+
* // Invert validation (fail if value is in blacklist)
|
|
601
|
+
* const blacklist = ["admin", "root"];
|
|
602
|
+
* const isBlacklisted = (name: string) =>
|
|
603
|
+
* Result.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
|
|
604
|
+
* .flip(); // Ok if blacklisted, Err if not
|
|
605
|
+
* ```
|
|
606
|
+
*/
|
|
607
|
+
flip(): Result<E, T>;
|
|
608
|
+
/**
|
|
609
|
+
* Converts Result to Option, discarding error information.
|
|
610
|
+
*
|
|
611
|
+
* - Ok(value) → Some(value)
|
|
612
|
+
* - Err(error) → None
|
|
613
|
+
*
|
|
614
|
+
* Use when you only care about presence/absence of a value, not the error.
|
|
615
|
+
*
|
|
616
|
+
* @returns Option<T> - Some if Ok, None if Err
|
|
617
|
+
*
|
|
618
|
+
* @example
|
|
619
|
+
* ```ts
|
|
620
|
+
* Result.Ok(42).toOption(); // Some(42)
|
|
621
|
+
* Result.Err("fail").toOption(); // None
|
|
622
|
+
*
|
|
623
|
+
* // Safe user lookup
|
|
624
|
+
* const userOpt = fetchUser(id).toOption();
|
|
625
|
+
* // User or None, regardless of why fetch failed
|
|
626
|
+
* ```
|
|
627
|
+
*
|
|
628
|
+
* @see Option.toResult
|
|
629
|
+
*/
|
|
120
630
|
toOption(): Option<T>;
|
|
121
|
-
/**
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
631
|
+
/**
|
|
632
|
+
* Resolves the inner promise while preserving Result structure.
|
|
633
|
+
*
|
|
634
|
+
* @returns Promise of Result with awaited value or Err
|
|
635
|
+
*/
|
|
636
|
+
toPromise(): Promise<Result<Awaited<T>, E>>;
|
|
637
|
+
/**
|
|
638
|
+
* Maps over array elements inside a Result<Array<T>, E>.
|
|
639
|
+
*
|
|
640
|
+
* Applies the mapper function to each element if the Result is Ok and
|
|
641
|
+
* contains an array. Propagates Err unchanged.
|
|
642
|
+
*
|
|
643
|
+
* @param mapper - Function to map over each array element
|
|
644
|
+
* @returns Result<Array<Out>, E> with mapped array or propagated error
|
|
645
|
+
* @throws Error if the Result is Ok but value is not an array
|
|
646
|
+
*
|
|
647
|
+
* @example
|
|
648
|
+
* ```ts
|
|
649
|
+
* Result.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
|
|
650
|
+
* Result.Err("fail").innerMap((x) => x * 2); // Err("fail")
|
|
651
|
+
* ```
|
|
652
|
+
*/
|
|
653
|
+
innerMap<In, E, Out>(this: Result<Array<In>, E>, mapper: (val: NoInfer<In>) => Out): Result<Array<Out>, E>;
|
|
654
|
+
/**
|
|
655
|
+
* Recovers from Err by providing a fallback Result.
|
|
656
|
+
*
|
|
657
|
+
* If Ok, returns self unchanged.
|
|
658
|
+
*
|
|
659
|
+
* @template T2 - Fallback success type
|
|
660
|
+
* @template E2 - Fallback error type
|
|
661
|
+
* @param fn - Function to produce a fallback Result from the error
|
|
662
|
+
* @returns Original Ok or fallback Result
|
|
663
|
+
*/
|
|
664
|
+
orElse<T2, E2>(fn: (err: E) => Result<T2, E2>): Result<T | T2, E2>;
|
|
665
|
+
/**
|
|
666
|
+
* Creates a Result from a nullable value.
|
|
667
|
+
*
|
|
668
|
+
* Returns Err when the value is null or undefined, otherwise Ok.
|
|
669
|
+
*
|
|
670
|
+
* @template T - Input value type
|
|
671
|
+
* @template E - Error type
|
|
672
|
+
* @param val - Value to wrap
|
|
673
|
+
* @param error - Error value for null/undefined
|
|
674
|
+
* @returns Ok with value or Err with error
|
|
675
|
+
*/
|
|
676
|
+
static fromNullable<T, E>(this: void, val: T | null | undefined, error: E): Result<NonNullable<T>, E>;
|
|
677
|
+
/**
|
|
678
|
+
* Creates a Result based on a predicate.
|
|
679
|
+
*
|
|
680
|
+
* Returns Ok when predicate passes, otherwise Err.
|
|
681
|
+
*
|
|
682
|
+
* @template T - Input value type
|
|
683
|
+
* @template E - Error type
|
|
684
|
+
* @param val - Value to test
|
|
685
|
+
* @param pred - Predicate to decide Ok vs Err
|
|
686
|
+
* @param error - Error value for predicate failure
|
|
687
|
+
* @returns Ok with value or Err with error
|
|
688
|
+
*/
|
|
689
|
+
static fromPredicate<T, E>(this: void, val: T, pred: (v: T) => boolean, error: E): Result<T, E>;
|
|
690
|
+
/**
|
|
691
|
+
* Wraps a Promise<Result<T, E>> as Result<Promise<T>, E>.
|
|
692
|
+
*
|
|
693
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the inner promise fails later,
|
|
694
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
695
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
696
|
+
*
|
|
697
|
+
* @template U - Success value type
|
|
698
|
+
* @template F - Error type
|
|
699
|
+
* @param promise - Promise resolving to a Result
|
|
700
|
+
* @returns Result containing a Promise of the success value
|
|
701
|
+
*/
|
|
702
|
+
static fromPromise<U, F>(this: void, promise: Promise<Result<U, F>>): Result<Promise<U>, F>;
|
|
703
|
+
/**
|
|
704
|
+
* Catches synchronous exceptions and converts them to Err.
|
|
705
|
+
*
|
|
706
|
+
* @template T - Success value type
|
|
707
|
+
* @template E - Error type
|
|
708
|
+
* @param fn - Function that may throw
|
|
709
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
710
|
+
* @returns Ok with return value or Err with mapped error
|
|
711
|
+
*/
|
|
712
|
+
static tryCatch<T, E = unknown>(this: void, fn: () => T, errorMapper?: (e: unknown) => E): Result<T, E>;
|
|
713
|
+
/**
|
|
714
|
+
* Catches async exceptions and converts them to Err.
|
|
715
|
+
*
|
|
716
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the async work fails later,
|
|
717
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
718
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
719
|
+
*
|
|
720
|
+
* @template T - Success value type
|
|
721
|
+
* @template E - Error type
|
|
722
|
+
* @param fn - Async function that may throw
|
|
723
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
724
|
+
* @returns Result containing a Promise of the success value
|
|
725
|
+
*/
|
|
726
|
+
static tryAsyncCatch<T, E = unknown>(this: void, fn: () => Promise<T>, errorMapper?: (e: unknown) => E): Result<Promise<T>, E>;
|
|
727
|
+
/**
|
|
728
|
+
* Makes Result iterable for use with generator-based syntax.
|
|
729
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
730
|
+
*
|
|
731
|
+
* @example
|
|
732
|
+
* ```ts
|
|
733
|
+
* const result = Result.gen(function* () {
|
|
734
|
+
* const value = yield* Result.Ok(42);
|
|
735
|
+
* return value * 2;
|
|
736
|
+
* });
|
|
737
|
+
* ```
|
|
738
|
+
*/
|
|
739
|
+
[Symbol.iterator](): Generator<Result<T, E>, T, unknown>;
|
|
740
|
+
/**
|
|
741
|
+
* Makes Result iterable for use with async generator-based syntax.
|
|
742
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* ```ts
|
|
746
|
+
* const result = await Result.asyncGen(async function* () {
|
|
747
|
+
* const value = yield* $(Result.Ok(42));
|
|
748
|
+
* return value * 2;
|
|
749
|
+
* });
|
|
750
|
+
* ```
|
|
751
|
+
*/
|
|
752
|
+
[Symbol.asyncIterator](): AsyncGenerator<Result<T, E>, T, unknown>;
|
|
753
|
+
/**
|
|
754
|
+
* Generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
755
|
+
* Provides imperative-style code while maintaining functional error handling.
|
|
756
|
+
*
|
|
757
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
758
|
+
* recursion to avoid stack overflow on deep chains.
|
|
759
|
+
*
|
|
760
|
+
* @example
|
|
761
|
+
* ```ts
|
|
762
|
+
* const result = Result.gen(function* () {
|
|
763
|
+
* const a = yield* Result.Ok(1);
|
|
764
|
+
* const b = yield* Result.Ok(2);
|
|
765
|
+
* return a + b;
|
|
766
|
+
* });
|
|
767
|
+
* // Result<number, never>
|
|
768
|
+
* ```
|
|
769
|
+
*/
|
|
770
|
+
static gen<Eff extends Result<any, any>, T>(this: void, genFn: () => Generator<Eff, T, any>): Result<T, ExtractError<Eff>>;
|
|
771
|
+
/**
|
|
772
|
+
* Generator-based syntax for chaining Result operations (with adapter).
|
|
773
|
+
* Uses an adapter function ($) for improved type inference.
|
|
774
|
+
*
|
|
775
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
776
|
+
* recursion to avoid stack overflow on deep chains.
|
|
777
|
+
*
|
|
778
|
+
* @example
|
|
779
|
+
* ```ts
|
|
780
|
+
* const result = Result.genAdapter(function* ($) {
|
|
781
|
+
* const a = yield* $(Result.Ok(1));
|
|
782
|
+
* const b = yield* $(Result.Ok(2));
|
|
783
|
+
* return a + b;
|
|
784
|
+
* });
|
|
785
|
+
* // Result<number, never>
|
|
786
|
+
* ```
|
|
787
|
+
*/
|
|
788
|
+
static genAdapter<Eff extends ResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E>(result: Result<A, E>) => ResultYieldWrap<A, E>) => Generator<Eff, T, any>): Result<T, ExtractResultError<Eff>>;
|
|
789
|
+
/**
|
|
790
|
+
* Async generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
791
|
+
* Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
|
|
792
|
+
*
|
|
793
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
794
|
+
* recursion to avoid stack overflow on deep chains.
|
|
795
|
+
*
|
|
796
|
+
* @example
|
|
797
|
+
* ```ts
|
|
798
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
799
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
800
|
+
* const result = await Result.asyncGen(async function* () {
|
|
801
|
+
* const a = yield* Result.Ok(1);
|
|
802
|
+
* const dataResult = yield* await fetchData(a);
|
|
803
|
+
* return a + dataResult.id;
|
|
804
|
+
* });
|
|
805
|
+
* // Result<number, never>
|
|
806
|
+
* ```
|
|
807
|
+
*/
|
|
808
|
+
static asyncGen<Eff extends Result<any, any>, T>(this: void, genFn: () => AsyncGenerator<Eff, T, any>): Promise<Result<T, ExtractError<Eff>>>;
|
|
809
|
+
/**
|
|
810
|
+
* Async generator-based syntax for chaining Result operations (with adapter).
|
|
811
|
+
* Uses an adapter function ($) for improved type inference.
|
|
812
|
+
* Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
|
|
813
|
+
*
|
|
814
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
815
|
+
* recursion to avoid stack overflow on deep chains.
|
|
816
|
+
*
|
|
817
|
+
* @example
|
|
818
|
+
* ```ts
|
|
819
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
820
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
821
|
+
* const result = await Result.asyncGenAdapter(async function* ($) {
|
|
822
|
+
* const a = yield* $(Result.Ok(1));
|
|
823
|
+
* const data = yield* $(fetchData(a));
|
|
824
|
+
* return a + data.id;
|
|
825
|
+
* });
|
|
826
|
+
* // Result<number, never>
|
|
827
|
+
* ```
|
|
828
|
+
*/
|
|
829
|
+
static asyncGenAdapter<Eff extends AsyncResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E2>(result: Result<A, E2> | Promise<Result<A, E2>>) => AsyncResultYieldWrap<A, E2>) => AsyncGenerator<Eff, T, any>): Promise<Result<T, ExtractAsyncResultError<Eff>>>;
|
|
139
830
|
}
|
|
140
831
|
//#endregion
|
|
141
832
|
export { CombineResults, Result, UnitResult, UnwrapResult };
|