@carbonteq/fp 0.8.2 → 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.
Files changed (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +237 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
@@ -0,0 +1,1127 @@
1
+ import { UNIT } from "./unit.mjs";
2
+ import { ExperimentalOption } from "./option-experimental.mjs";
3
+
4
+ //#region src/result-experimental.d.ts
5
+ /** ExperimentalResult alias for success-without-payload operations. */
6
+ type UnitResult<E = never> = ExperimentalResult<UNIT, E>;
7
+ /** Extracts `{ ok, err }` branch types from an ExperimentalResult type. */
8
+ type UnwrapResult<T extends ExperimentalResult<unknown, unknown>> = T extends ExperimentalResult<infer U, infer E> ? {
9
+ ok: U;
10
+ err: E;
11
+ } : never;
12
+ type CombinedResultOk<T extends ExperimentalResult<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["ok"] };
13
+ type CombinedResultErr<T extends ExperimentalResult<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["err"] }[number];
14
+ /** Combines a tuple of ExperimentalResults into one result of tuple values. */
15
+ type CombineResults<T extends ExperimentalResult<unknown, unknown>[]> = ExperimentalResult<CombinedResultOk<T>, CombinedResultErr<T>>;
16
+ interface MatchCases<T, E, U> {
17
+ Ok: (val: T) => U;
18
+ Err: (err: E) => U;
19
+ }
20
+ /**
21
+ * Wrapper that makes Result yieldable with proper type tracking.
22
+ * The Generator signature ensures TypeScript tracks the inner type T.
23
+ *
24
+ * @internal
25
+ */
26
+ declare class ResultYieldWrap<T, E> {
27
+ readonly result: ExperimentalResult<T, E>;
28
+ constructor(result: ExperimentalResult<T, E>);
29
+ [Symbol.iterator](): Generator<ResultYieldWrap<T, E>, T, unknown>;
30
+ }
31
+ /**
32
+ * Wrapper that makes Result yieldable in async generators with proper type tracking.
33
+ * Supports Promise<Result<T, E>> for async result chaining.
34
+ *
35
+ * @internal
36
+ */
37
+ declare class AsyncResultYieldWrap<T, E> {
38
+ readonly result: Promise<ExperimentalResult<T, E>>;
39
+ constructor(result: Promise<ExperimentalResult<T, E>>);
40
+ [Symbol.asyncIterator](): AsyncGenerator<AsyncResultYieldWrap<T, E>, T, unknown>;
41
+ }
42
+ /** Extract error type from yielded values */
43
+ type ExtractResultError<T> = T extends ResultYieldWrap<any, infer E> ? E : never;
44
+ /** Extract error type from async yielded values */
45
+ type ExtractAsyncResultError<T> = T extends AsyncResultYieldWrap<any, infer E> ? E : never;
46
+ /** Extract error type directly from ExperimentalResult */
47
+ type ExtractError<T> = T extends ExperimentalResult<any, infer E> ? E : never;
48
+ /**
49
+ * Experimental Result variant with explicit async companion methods.
50
+ */
51
+ declare class ExperimentalResult<T, E> {
52
+ #private;
53
+ /** Discriminant tag for type-level identification */
54
+ readonly _tag: "Ok" | "Err";
55
+ private constructor();
56
+ /** Singleton UNIT_RESULT for void-success operations */
57
+ static readonly UNIT_RESULT: ExperimentalResult<UNIT, never>;
58
+ /** Create an Ok containing the given value */
59
+ static Ok<T, E = never>(this: void, val: T): ExperimentalResult<T, E>;
60
+ /** Create an Err containing the given error */
61
+ static Err<E, T = never>(this: void, err: E): ExperimentalResult<T, E>;
62
+ /**
63
+ * Type guard for Ok state.
64
+ *
65
+ * Narrows the type, making `T` accessible and `E` equivalent to `never` in
66
+ * the true branch.
67
+ *
68
+ * @returns `true` if this Result is Ok
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * const result = ExperimentalResult.Ok(42);
73
+ * if (result.isOk()) {
74
+ * // TypeScript knows value is accessible: 42
75
+ * console.log(result.unwrap()); // 42
76
+ * }
77
+ * ```
78
+ *
79
+ * @see isErr
80
+ */
81
+ isOk(): this is ExperimentalResult<T, never>;
82
+ /**
83
+ * Type guard for Err state.
84
+ *
85
+ * Narrows the type, making `E` accessible and `T` equivalent to `never` in
86
+ * the true branch.
87
+ *
88
+ * @returns `true` if this Result is Err
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * const result = ExperimentalResult.Err("failed");
93
+ * if (result.isErr()) {
94
+ * // TypeScript knows error is accessible: "failed"
95
+ * console.log(result.unwrapErr()); // "failed"
96
+ * }
97
+ * ```
98
+ *
99
+ * @see isOk
100
+ */
101
+ isErr(): this is ExperimentalResult<never, E>;
102
+ /**
103
+ * Type guard for Unit value.
104
+ *
105
+ * Returns `true` when the Ok value is the `UNIT` singleton, used for void-success
106
+ * operations (e.g., side-effecting functions that return nothing on success).
107
+ *
108
+ * @returns `true` if this Result is Ok containing UNIT
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * function saveToDb(): ExperimentalResult<UNIT, DbError> {
113
+ * // ... save logic
114
+ * return ExperimentalResult.UNIT_RESULT;
115
+ * }
116
+ *
117
+ * const result = saveToDb();
118
+ * if (result.isUnit()) {
119
+ * console.log("Saved successfully");
120
+ * }
121
+ * ```
122
+ */
123
+ isUnit(): this is ExperimentalResult<UNIT, never>;
124
+ /**
125
+ * Returns a string representation of the Result.
126
+ *
127
+ * Useful for debugging and logging. Shows "Result::Ok" or "Result::Err" with
128
+ * the contained value or error.
129
+ *
130
+ * @returns String representation in format "Result::Ok<value>" or "Result::Err<error>"
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * ExperimentalResult.Ok(42).toString(); // "Result::Ok<42>"
135
+ * ExperimentalResult.Err("fail").toString(); // "Result::Err<fail>"
136
+ * ```
137
+ */
138
+ toString(): string;
139
+ /**
140
+ * Returns the contained value or throws.
141
+ *
142
+ * If the Result is Err and the error extends Error, the original error is re-thrown
143
+ * (preserving stack trace). Otherwise, throws `UnwrappedOkWithErr`.
144
+ *
145
+ * **Use with caution**: Prefer `unwrapOr`, `unwrapOrElse`, or `match` for safer
146
+ * error handling.
147
+ *
148
+ * @throws The original error if E extends Error, otherwise `UnwrappedOkWithErr`
149
+ * @returns The contained value if Ok
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * ExperimentalResult.Ok(42).unwrap(); // 42
154
+ * ExperimentalResult.Err(new Error("fail")).unwrap(); // throws Error("fail")
155
+ * ExperimentalResult.Err("fail").unwrap(); // throws UnwrappedOkWithErr
156
+ * ```
157
+ *
158
+ * @see unwrapOr
159
+ * @see unwrapOrElse
160
+ * @see safeUnwrap
161
+ */
162
+ unwrap(): T;
163
+ /**
164
+ * Returns the contained error or throws.
165
+ *
166
+ * **Use with caution**: Prefer `match` or `isErr` check for safer error access.
167
+ *
168
+ * @throws `UnwrappedErrWithOk` if the Result is Ok
169
+ * @returns The contained error if Err
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * ExperimentalResult.Err("fail").unwrapErr(); // "fail"
174
+ * ExperimentalResult.Ok(42).unwrapErr(); // throws UnwrappedErrWithOk
175
+ * ```
176
+ */
177
+ unwrapErr(): E;
178
+ /**
179
+ * Returns the contained value or the provided default.
180
+ *
181
+ * A safe alternative to `unwrap` for providing fallback values.
182
+ *
183
+ * @param defaultValue - The value to return if Err
184
+ * @returns The contained value if Ok, otherwise defaultValue
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * ExperimentalResult.Ok(42).unwrapOr(0); // 42
189
+ * ExperimentalResult.Err("fail").unwrapOr(0); // 0
190
+ * ```
191
+ *
192
+ * @see unwrapOrElse
193
+ * @see safeUnwrap
194
+ */
195
+ unwrapOr(defaultValue: T): T;
196
+ /**
197
+ * Returns the contained value or computes a default from the error.
198
+ *
199
+ * Use when the fallback value depends on the error content.
200
+ *
201
+ * @param fn - Function that receives the error and returns a fallback value
202
+ * @returns The contained value if Ok, otherwise the result of fn(error)
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const result = ExperimentalResult.Err("Not found");
207
+ * result.unwrapOrElse((err) => `Default: ${err}`); // "Default: Not found"
208
+ *
209
+ * ExperimentalResult.Ok(42).unwrapOrElse((err) => 0); // 42
210
+ * ```
211
+ *
212
+ * @see unwrapOr
213
+ * @see unwrap
214
+ */
215
+ unwrapOrElse(fn: (err: E) => T): T;
216
+ /**
217
+ * Safely unwraps the value, returning null for Err.
218
+ *
219
+ * A convenience method for JavaScript-friendly null handling.
220
+ *
221
+ * @returns The contained value if Ok, otherwise null
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * ExperimentalResult.Ok(42).safeUnwrap(); // 42
226
+ * ExperimentalResult.Err("fail").safeUnwrap(); // null
227
+ *
228
+ * // Useful for null coalescing
229
+ * const value = result.safeUnwrap() ?? "default";
230
+ * ```
231
+ *
232
+ * @see unwrapOr
233
+ */
234
+ safeUnwrap(): T | null;
235
+ /**
236
+ * Exhaustive pattern matching on Result state.
237
+ *
238
+ * Handles both Ok and Err branches with provided functions, ensuring all cases
239
+ * are covered. TypeScript enforces that both branches are specified.
240
+ *
241
+ * @param cases - Object containing Ok and Err handler functions
242
+ * @returns The result of calling the appropriate handler
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * const message = ExperimentalResult.Ok(42).match({
247
+ * Ok: (val) => `Success: ${val}`,
248
+ * Err: (err) => `Failed: ${err}`,
249
+ * });
250
+ * // "Success: 42"
251
+ *
252
+ * // For side effects
253
+ * result.match({
254
+ * Ok: (data) => console.log("Got:", data),
255
+ * Err: (error) => console.error("Error:", error),
256
+ * });
257
+ * ```
258
+ */
259
+ match<U>(cases: MatchCases<T, E, U>): U;
260
+ /**
261
+ * Pattern matches using positional arguments (FP convention alias for `match`).
262
+ *
263
+ * This is a more concise alternative to `match` using positional arguments
264
+ * instead of an object. Familiar to developers from Scala, Haskell, and other FP languages.
265
+ *
266
+ * @template U - The result type of both branches
267
+ * @param onOk - Handler called with the value if `Ok`
268
+ * @param onErr - Handler called with the error if `Err`
269
+ * @returns The result of calling the appropriate handler
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * const result = ExperimentalResult.Ok(42).fold(
274
+ * (value) => `Success: ${value}`,
275
+ * (error) => `Failed: ${error}`
276
+ * );
277
+ * // "Success: 42"
278
+ *
279
+ * const errResult = ExperimentalResult.Err("network error").fold(
280
+ * (value) => `Success: ${value}`,
281
+ * (error) => `Failed: ${error}`
282
+ * );
283
+ * // "Failed: network error"
284
+ *
285
+ * // Equivalent to match:
286
+ * result.fold(onOk, onErr);
287
+ * result.match({ Ok: onOk, Err: onErr });
288
+ * ```
289
+ *
290
+ * @see {@link match} for object-based pattern matching
291
+ * @see {@link foldAsync} for async handlers
292
+ */
293
+ fold<U>(onOk: (val: T) => U, onErr: (err: E) => U): U;
294
+ /**
295
+ * Async pattern matching using positional arguments.
296
+ *
297
+ * Async variant of `fold` for when handlers return Promises.
298
+ *
299
+ * @template U - The result type of both branches
300
+ * @param onOk - Async handler called with the value if `Ok`
301
+ * @param onErr - Async handler called with the error if `Err`
302
+ * @returns Promise resolving to the result of the appropriate handler
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * const result = await ExperimentalResult.Ok(userId).foldAsync(
307
+ * async (id) => await fetchUserData(id),
308
+ * async (error) => await logAndGetFallback(error)
309
+ * );
310
+ *
311
+ * // Error recovery with logging
312
+ * const data = await apiResult.foldAsync(
313
+ * async (response) => await processResponse(response),
314
+ * async (error) => {
315
+ * await reportError(error);
316
+ * return getDefaultData();
317
+ * }
318
+ * );
319
+ * ```
320
+ *
321
+ * @see {@link fold} for synchronous handlers
322
+ * @see {@link matchAsync} for object-based async pattern matching
323
+ */
324
+ foldAsync<U>(onOk: (val: T) => Promise<U>, onErr: (err: E) => Promise<U>): Promise<U>;
325
+ /**
326
+ * Async pattern matching on both states of the Result.
327
+ *
328
+ * Async variant of `match` for when handlers return Promises.
329
+ *
330
+ * @template U - The result type of both branches
331
+ * @param cases - Object containing async handlers for both states
332
+ * @returns Promise resolving to the result of the appropriate handler
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * const result = await apiResult.matchAsync({
337
+ * Ok: async (data) => await processData(data),
338
+ * Err: async (error) => await handleError(error)
339
+ * });
340
+ *
341
+ * // With database operations
342
+ * const user = await findUserResult.matchAsync({
343
+ * Ok: async (user) => await enrichUserData(user),
344
+ * Err: async (error) => {
345
+ * await logError(error);
346
+ * return createGuestUser();
347
+ * }
348
+ * });
349
+ * ```
350
+ *
351
+ * @see {@link match} for synchronous pattern matching
352
+ * @see {@link foldAsync} for positional-argument async matching
353
+ */
354
+ matchAsync<U>(cases: {
355
+ Ok: (val: T) => Promise<U>;
356
+ Err: (err: E) => Promise<U>;
357
+ }): Promise<U>;
358
+ /**
359
+ * Pattern matches with a subset of cases, using a default for unhandled cases.
360
+ *
361
+ * Unlike `match` which requires all cases, `matchPartial` allows handling
362
+ * only specific cases with a fallback default value or function.
363
+ *
364
+ * @template U - The result type
365
+ * @param cases - Partial object with optional `Ok` and `Err` handlers
366
+ * @param getDefault - Lazy default function for unhandled cases
367
+ * @returns The result of the matching handler or the default
368
+ *
369
+ * @example
370
+ * ```ts
371
+ * // Only handle Ok, default for Err
372
+ * ExperimentalResult.Ok(42).matchPartial({ Ok: (v) => v * 2 }, () => 0); // 84
373
+ * ExperimentalResult.Err("fail").matchPartial({ Ok: (v) => v * 2 }, () => 0); // 0
374
+ *
375
+ * // Only handle Err for logging
376
+ * result.matchPartial({ Err: (e) => { logError(e); return null; } }, () => null);
377
+ *
378
+ * // Lazy default with function
379
+ * result.matchPartial(
380
+ * { Ok: (v) => process(v) },
381
+ * () => computeExpensiveDefault()
382
+ * );
383
+ * ```
384
+ *
385
+ * @see {@link match} for exhaustive pattern matching
386
+ */
387
+ matchPartial<U>(cases: Partial<MatchCases<T, E, U>>, getDefault: () => U): U;
388
+ /**
389
+ * Transforms the success value using the provided function.
390
+ *
391
+ * If the Result is Ok, applies the function to the value and wraps the result
392
+ * in a new Ok. If Err, propagates the error unchanged without calling the function.
393
+ *
394
+ * For async transformations, use `mapAsync` instead.
395
+ *
396
+ * @param fn - Function to transform the success value
397
+ * @returns Result<U, E> with transformed value or propagated error
398
+ *
399
+ * @example
400
+ * ```ts
401
+ * ExperimentalResult.Ok(42).map((x) => x * 2); // Ok(84)
402
+ * ExperimentalResult.Err("fail").map((x) => x * 2); // Err("fail")
403
+ * ```
404
+ *
405
+ * @see mapAsync
406
+ * @see flatMap
407
+ */
408
+ map<U>(fn: (val: T) => Promise<U>): never;
409
+ map<U>(fn: (val: T) => U): ExperimentalResult<U, E>;
410
+ /**
411
+ * Transforms the success value using an async function.
412
+ *
413
+ * Same as `map` but for async mappers. Returns `Promise<Result<U, E>>`.
414
+ *
415
+ * @param fn - Async function to transform the success value
416
+ * @returns Promise resolving to Result<U, E> with transformed value or propagated error
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * await ExperimentalResult.Ok(42).mapAsync(async (x) => x * 2); // Promise<Ok(84)>
421
+ * await ExperimentalResult.Err("fail").mapAsync(async (x) => x * 2); // Promise<Err("fail")>
422
+ * ```
423
+ *
424
+ * @see map
425
+ */
426
+ mapAsync<U>(fn: (val: T) => Promise<U>): Promise<ExperimentalResult<U, E>>;
427
+ /**
428
+ * Chains operations that return Results, flattening nested Results.
429
+ *
430
+ * If the Result is Ok, applies the function (which returns a new Result) and
431
+ * returns that Result directly. If Err, propagates the error unchanged.
432
+ *
433
+ * Error types are unified: `Result<U, E | E2>`.
434
+ *
435
+ * For async operations, use `flatMapAsync` instead.
436
+ *
437
+ * @param fn - Function that returns a Result
438
+ * @returns Result<U, E | E2> from the function or propagated error
439
+ *
440
+ * @example
441
+ * ```ts
442
+ * // Success chain
443
+ * ExperimentalResult.Ok(42)
444
+ * .flatMap((x) => ExperimentalResult.Ok(x + 1)) // Ok(43)
445
+ * .flatMap((x) => ExperimentalResult.Err("too big")); // Err("too big")
446
+ *
447
+ * // Error propagation
448
+ * ExperimentalResult.Err("initial").flatMap((x) => ExperimentalResult.Ok(x + 1)); // Err("initial")
449
+ * ```
450
+ *
451
+ * @see flatMapAsync
452
+ * @see map
453
+ * @see flatZip
454
+ */
455
+ flatMap<U, E2>(fn: (val: T) => ExperimentalResult<U, E2>): ExperimentalResult<U, E | E2>;
456
+ /**
457
+ * Chains async operations that return Results.
458
+ *
459
+ * Same as `flatMap` but for async Result-returning functions.
460
+ * Returns `Promise<Result<U, E | E2>>`.
461
+ *
462
+ * @param fn - Async function that returns a Promise resolving to Result
463
+ * @returns Promise resolving to Result<U, E | E2>
464
+ *
465
+ * @example
466
+ * ```ts
467
+ * const fetchUser = (id: number): Promise<Result<User, string>> =>
468
+ * Promise.resolve(ExperimentalResult.Ok({ id, name: "Alice" }));
469
+ *
470
+ * await ExperimentalResult.Ok(42)
471
+ * .flatMapAsync(fetchUser)
472
+ * .then((r) => r.map((user) => user.name));
473
+ * // Promise<Ok("Alice")>
474
+ * ```
475
+ *
476
+ * @see flatMap
477
+ */
478
+ flatMapAsync<U, E2>(fn: (val: T) => Promise<ExperimentalResult<U, E2>>): Promise<ExperimentalResult<U, E | E2>>;
479
+ /**
480
+ * Pairs the original value with a derived value in a tuple.
481
+ *
482
+ * Unlike `map` which replaces the value, `zip` keeps the original and adds
483
+ * the derived value, creating `[original, derived]`.
484
+ *
485
+ * For async derivations, use `zipAsync` instead.
486
+ *
487
+ * @param fn - Function to derive a value from the original
488
+ * @returns Result<[T, U], E> containing tuple of original and derived values
489
+ *
490
+ * @example
491
+ * ```ts
492
+ * ExperimentalResult.Ok(42).zip((x) => x * 10); // Ok([42, 420])
493
+ * ExperimentalResult.Err("fail").zip((x) => x * 10); // Err("fail")
494
+ *
495
+ * // Keep original while computing related value
496
+ * ExperimentalResult.Ok(user).zip((u) => u.permissions.length); // Ok([user, 5])
497
+ * ```
498
+ *
499
+ * @see zipAsync
500
+ * @see flatZip
501
+ * @see map
502
+ */
503
+ zip<U>(fn: (val: T) => Promise<U>): never;
504
+ zip<U>(fn: (val: T) => U): ExperimentalResult<[prev: T, current: U], E>;
505
+ /**
506
+ * Pairs the original value with a derived async value.
507
+ *
508
+ * Same as `zip` but for async derivation functions.
509
+ * Returns `Promise<Result<[T, U], E>>`.
510
+ *
511
+ * @param fn - Async function to derive a value from the original
512
+ * @returns Promise resolving to Result<[T, U], E>
513
+ *
514
+ * @example
515
+ * ```ts
516
+ * await ExperimentalResult.Ok(42).zipAsync(async (x) => x * 10); // Promise<Ok([42, 420])>
517
+ * ```
518
+ *
519
+ * @see zip
520
+ */
521
+ zipAsync<U>(fn: (val: T) => Promise<U>): Promise<ExperimentalResult<[T, U], E>>;
522
+ /**
523
+ * Combines the current Result with another independent Result in a tuple.
524
+ *
525
+ * Unlike `zip` which derives a value from the original, `flatZip` works with
526
+ * two independent Results. If either is Err, propagates the first error.
527
+ *
528
+ * For async Results, use `flatZipAsync` instead.
529
+ *
530
+ * @param fn - Function that receives the value and returns another Result
531
+ * @returns Result<[T, U], E | E2> containing tuple of both values, or error
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * ExperimentalResult.Ok(42)
536
+ * .flatZip((x) => ExperimentalResult.Ok(x + 5)) // Ok([42, 47])
537
+ * .flatZip(([a, b]) => ExperimentalResult.Err("x")); // Err("x")
538
+ *
539
+ * ExperimentalResult.Ok(42).flatZip((x) => ExperimentalResult.Err("fail")); // Err("fail")
540
+ * ExperimentalResult.Err("init").flatZip((x) => ExperimentalResult.Ok(5)); // Err("init")
541
+ * ```
542
+ *
543
+ * @see flatZipAsync
544
+ * @see zip
545
+ * @see flatMap
546
+ */
547
+ flatZip<U, E2>(fn: (val: T) => ExperimentalResult<U, E2>): ExperimentalResult<[T, U], E | E2>;
548
+ /**
549
+ * Combines the current Result with another independent async Result in a tuple.
550
+ *
551
+ * Same as `flatZip` but for async Result-returning functions.
552
+ * Returns `Promise<Result<[T, U], E | E2>>`.
553
+ *
554
+ * @param fn - Async function that receives the value and returns a Promise resolving to Result
555
+ * @returns Promise resolving to Result<[T, U], E | E2>
556
+ *
557
+ * @example
558
+ * ```ts
559
+ * const fetchData = (id: number): Promise<Result<Data, string>> =>
560
+ * Promise.resolve(ExperimentalResult.Ok({ id, value: 100 }));
561
+ *
562
+ * await ExperimentalResult.Ok(42).flatZipAsync(fetchData); // Promise<Ok([42, {id: 42, value: 100}])>
563
+ * ```
564
+ *
565
+ * @see flatZip
566
+ */
567
+ flatZipAsync<U, E2>(fn: (val: T) => Promise<ExperimentalResult<U, E2>>): Promise<ExperimentalResult<[T, U], E | E2>>;
568
+ /**
569
+ * Transforms the error value while preserving the success value.
570
+ *
571
+ * If the Result is Err, applies the function to the error. If Ok, returns
572
+ * the Ok unchanged without calling the function.
573
+ *
574
+ * For async transformations, use `mapErrAsync` instead.
575
+ *
576
+ * @param fn - Function to transform the error
577
+ * @returns Result<T, E2> with transformed error or original Ok
578
+ *
579
+ * @example
580
+ * ```ts
581
+ * ExperimentalResult.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
582
+ * ExperimentalResult.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
583
+ *
584
+ * // Add context to errors
585
+ * fetchData()
586
+ * .mapErr((e) => new ContextualError("Failed to fetch data", e));
587
+ * ```
588
+ *
589
+ * @see mapErrAsync
590
+ * @see mapBoth
591
+ */
592
+ mapErr<E2>(fn: (err: E) => Promise<E2>): never;
593
+ mapErr<E2>(fn: (err: E) => E2): ExperimentalResult<T, E2>;
594
+ /**
595
+ * Transforms the error value using an async function.
596
+ *
597
+ * Same as `mapErr` but for async error transformations.
598
+ * Returns `Promise<Result<T, E2>>`.
599
+ *
600
+ * @param fn - Async function to transform the error
601
+ * @returns Promise resolving to Result<T, E2> with transformed error or original Ok
602
+ *
603
+ * @example
604
+ * ```ts
605
+ * await ExperimentalResult.Err("timeout").mapErrAsync(async (e) => await formatError(e));
606
+ * // Promise<Err("Timeout occurred: timeout")>
607
+ * ```
608
+ *
609
+ * @see mapErr
610
+ */
611
+ mapErrAsync<E2>(fn: (err: E) => Promise<E2>): Promise<ExperimentalResult<T, E2>>;
612
+ /**
613
+ * Transforms both the success value and error value simultaneously.
614
+ *
615
+ * Applies the appropriate function based on the Result state. Useful for
616
+ * formatting or decorating both branches.
617
+ *
618
+ * For async transformations, use `mapBothAsync` instead.
619
+ *
620
+ * @param fnOk - Function to transform the success value
621
+ * @param fnErr - Function to transform the error
622
+ * @returns Result<T2, E2> with transformed value or error
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * ExperimentalResult.Ok(42).mapBoth(
627
+ * (val) => `Success: ${val}`,
628
+ * (err) => `Failure: ${err}`
629
+ * ); // Ok("Success: 42")
630
+ *
631
+ * ExperimentalResult.Err("timeout").mapBoth(
632
+ * (val) => `Success: ${val}`,
633
+ * (err) => `Failure: ${err}`
634
+ * ); // Err("Failure: timeout")
635
+ * ```
636
+ *
637
+ * @see mapBothAsync
638
+ * @see map
639
+ * @see mapErr
640
+ */
641
+ mapBoth<T2, E2>(fnOk: (val: T) => Promise<T2>, fnErr: (err: E) => E2): never;
642
+ mapBoth<T2, E2>(fnOk: (val: T) => T2, fnErr: (err: E) => Promise<E2>): never;
643
+ mapBoth<T2, E2>(fnOk: (val: T) => T2, fnErr: (err: E) => E2): ExperimentalResult<T2, E2>;
644
+ /**
645
+ * Transforms both the success value and error value using async functions.
646
+ *
647
+ * Same as `mapBoth` but for async transformations.
648
+ * Returns `Promise<Result<T2, E2>>`.
649
+ *
650
+ * @param fnOk - Async function to transform the success value
651
+ * @param fnErr - Async function to transform the error
652
+ * @returns Promise resolving to Result<T2, E2> with transformed value or error
653
+ *
654
+ * @example
655
+ * ```ts
656
+ * await ExperimentalResult.Ok(42).mapBothAsync(
657
+ * async (val) => await formatSuccess(val),
658
+ * async (err) => await formatError(err)
659
+ * );
660
+ * // Promise<Ok("Success: 42")>
661
+ * ```
662
+ *
663
+ * @see mapBoth
664
+ */
665
+ mapBothAsync<T2, E2>(fnOk: (val: T) => Promise<T2>, fnErr: (err: E) => Promise<E2>): Promise<ExperimentalResult<T2, E2>>;
666
+ /**
667
+ * Recovers from an error by providing a fallback Result.
668
+ *
669
+ * If the Result is Ok, returns it unchanged. If Err, calls the function
670
+ * with the error to produce a new Result.
671
+ *
672
+ * For async recovery, use `orElseAsync` instead.
673
+ *
674
+ * @param fn - Function that receives the error and returns a fallback Result
675
+ * @returns Result<T, E2> - original Ok or fallback Result from fn
676
+ *
677
+ * @example
678
+ * ```ts
679
+ * // Recovery with fallback
680
+ * fetchFromPrimary()
681
+ * .orElse((e) => fetchFromBackup())
682
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
683
+ *
684
+ * // Ok passes through unchanged
685
+ * ExperimentalResult.Ok(42).orElse((e) => ExperimentalResult.Ok(0)); // Ok(42)
686
+ *
687
+ * // Err triggers recovery
688
+ * ExperimentalResult.Err("not found").orElse((e) => ExperimentalResult.Ok(0)); // Ok(0)
689
+ * ExperimentalResult.Err("fail").orElse((e) => ExperimentalResult.Err("critical")); // Err("critical")
690
+ * ```
691
+ *
692
+ * @see orElseAsync
693
+ */
694
+ orElse<E2>(fn: (err: E) => ExperimentalResult<T, E2>): ExperimentalResult<T, E2>;
695
+ /**
696
+ * Recovers from an error by providing a fallback async Result.
697
+ *
698
+ * Same as `orElse` but for async Result-returning functions.
699
+ * Returns `Promise<Result<T, E2>>`.
700
+ *
701
+ * @param fn - Async function that receives the error and returns a Promise resolving to fallback Result
702
+ * @returns Promise resolving to Result<T, E2> - original Ok or fallback Result from fn
703
+ *
704
+ * @example
705
+ * ```ts
706
+ * await fetchData().orElseAsync(async (e) => {
707
+ * return await fetchBackupData();
708
+ * });
709
+ * ```
710
+ *
711
+ * @see orElse
712
+ */
713
+ orElseAsync<E2>(fn: (err: E) => Promise<ExperimentalResult<T, E2>>): Promise<ExperimentalResult<T, E2>>;
714
+ /**
715
+ * Runs multiple validators on the Ok value, collecting ALL errors.
716
+ *
717
+ * Unlike most Result methods which short-circuit on the first error,
718
+ * `validate` runs ALL validators and collects all errors together.
719
+ * This is useful for form validation where you want to show all errors at once.
720
+ *
721
+ * If the Result is Err, returns it unchanged without running validators.
722
+ *
723
+ * Supports both sync and async validators. If any validator is async,
724
+ * returns `Promise<Result<T, E | VE[]>>`.
725
+ *
726
+ * @param validators - Array of validator functions that return Result
727
+ * @returns Result<T, E | VE[]> with original value or array of all errors
728
+ *
729
+ * @example
730
+ * ```ts
731
+ * const validators = [
732
+ * (x: number) => x > 0 ? ExperimentalResult.Ok(true) : ExperimentalResult.Err("must be positive"),
733
+ * (x: number) => x < 100 ? ExperimentalResult.Ok(true) : ExperimentalResult.Err("must be < 100"),
734
+ * (x: number) => x % 2 === 0 ? ExperimentalResult.Ok(true) : ExperimentalResult.Err("must be even"),
735
+ * ];
736
+ *
737
+ * ExperimentalResult.Ok(42).validate(validators); // Ok(42)
738
+ * ExperimentalResult.Ok(101).validate(validators); // Err(["must be < 100"])
739
+ * ExperimentalResult.Ok(-5).validate(validators); // Err(["must be positive", "must be even"])
740
+ * ExperimentalResult.Err("init").validate(validators); // Err("init") - validators not run
741
+ *
742
+ * // With async validators (returns Promise<Result<...>>)
743
+ * await ExperimentalResult.Ok(data).validate([
744
+ * async (d) => await validateEmail(d),
745
+ * async (d) => await validatePhone(d),
746
+ * ]);
747
+ * ```
748
+ *
749
+ * @see validateAsync
750
+ * @see all
751
+ */
752
+ validate<VE extends unknown[]>(validators: { [K in keyof VE]: (val: T) => ExperimentalResult<unknown, VE[K]> }): ExperimentalResult<T, E | VE[number][]>;
753
+ validate<VE extends unknown[]>(validators: { [K in keyof VE]: (val: T) => Promise<ExperimentalResult<unknown, VE[K]>> }): Promise<ExperimentalResult<T, E | VE[number][]>>;
754
+ /**
755
+ * Runs async validators on the Ok value, collecting ALL errors.
756
+ *
757
+ * Explicit async variant of `validate` for when all validators are async.
758
+ * Always returns `Promise<Result<T, E | VE[]>>`.
759
+ *
760
+ * @param validators - Array of async validator functions
761
+ * @returns Promise resolving to Result<T, E | VE[]> with original value or array of all errors
762
+ *
763
+ * @example
764
+ * ```ts
765
+ * // Form validation with async checks
766
+ * const validated = await ExperimentalResult.Ok(formData).validateAsync([
767
+ * async (d) => await checkEmailUnique(d.email),
768
+ * async (d) => await checkUsernameAvailable(d.username),
769
+ * ]);
770
+ *
771
+ * // Password validation against database
772
+ * await ExperimentalResult.Ok("password123!").validateAsync([
773
+ * async (pw) => await checkNotPreviousPassword(pw),
774
+ * async (pw) => await checkNotCommonPassword(pw),
775
+ * ]);
776
+ * ```
777
+ *
778
+ * @see validate
779
+ */
780
+ validateAsync<VE extends unknown[]>(validators: { [K in keyof VE]: (val: T) => Promise<ExperimentalResult<unknown, VE[K]>> }): Promise<ExperimentalResult<T, E | VE[number][]>>;
781
+ /**
782
+ * Combines multiple Results, collecting all values or all errors.
783
+ *
784
+ * Unlike typical Result behavior which short-circuits on first error,
785
+ * `all` collects ALL errors from all Results. This is useful when you
786
+ * want to show complete validation feedback.
787
+ *
788
+ * - All Ok → `Ok([...values])` with preserved tuple types
789
+ * - Any Err → `Err([...errors])` collecting ALL errors
790
+ *
791
+ * @param results - Variable number of Results to combine
792
+ * @returns Result with tuple of all values, or array of all errors
793
+ *
794
+ * @example
795
+ * ```ts
796
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Ok(2), ExperimentalResult.Ok(3)); // Ok([1, 2, 3])
797
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Err("a"), ExperimentalResult.Err("b")); // Err(["a", "b"])
798
+ * ExperimentalResult.all(); // Ok([])
799
+ *
800
+ * // Real-world: Parallel validation
801
+ * const [user, posts, likes] = await Promise.all([
802
+ * fetchUser(id),
803
+ * fetchPosts(id),
804
+ * fetchLikes(id),
805
+ * ]);
806
+ *
807
+ * const combined = ExperimentalResult.all(user, posts, likes);
808
+ * // Ok([User, Post[], Like[]]) or Err([...errors])
809
+ * ```
810
+ *
811
+ * @see any
812
+ * @see validate
813
+ */
814
+ static all<T extends ExperimentalResult<unknown, unknown>[]>(...results: T): ExperimentalResult<CombinedResultOk<T>, CombinedResultErr<T>[]>;
815
+ /**
816
+ * Returns the first Ok, or collects all errors if all are Err.
817
+ *
818
+ * Useful for fallback chains where you want the first success, but want
819
+ * to collect all errors if everything fails.
820
+ *
821
+ * - First Ok → Returns that Ok immediately
822
+ * - All Err → `Err([...all errors])`
823
+ *
824
+ * @param results - Variable number of Results to check
825
+ * @returns First Ok found, or Err with array of all errors
826
+ *
827
+ * @example
828
+ * ```ts
829
+ * ExperimentalResult.any(
830
+ * ExperimentalResult.Err("Error 1"),
831
+ * ExperimentalResult.Ok("First success"),
832
+ * ExperimentalResult.Ok("Second success"),
833
+ * ); // Ok("First success")
834
+ *
835
+ * ExperimentalResult.any(
836
+ * ExperimentalResult.Err("Error 1"),
837
+ * ExperimentalResult.Err("Error 2"),
838
+ * ExperimentalResult.Err("Error 3"),
839
+ * ); // Err(["Error 1", "Error 2", "Error 3"])
840
+ *
841
+ * // Fallback chain
842
+ * ExperimentalResult.any(
843
+ * fetchFromCache(key),
844
+ * fetchFromDb(key),
845
+ * fetchFromRemote(key),
846
+ * );
847
+ * ```
848
+ *
849
+ * @see all
850
+ */
851
+ static any<U, F>(...results: ExperimentalResult<U, F>[]): ExperimentalResult<U, F[]>;
852
+ /**
853
+ * Executes a side effect function for Ok values, then returns self.
854
+ *
855
+ * Useful for logging, debugging, or executing effects without breaking the
856
+ * method chain. The function is only called if the Result is Ok.
857
+ *
858
+ * For async side effects, use `tapAsync` instead.
859
+ *
860
+ * @param fn - Function to execute with the Ok value
861
+ * @returns The same Result (chainable)
862
+ *
863
+ * @example
864
+ * ```ts
865
+ * ExperimentalResult.Ok(42)
866
+ * .tap((x) => console.log(`Processing: ${x}`))
867
+ * .map((x) => x * 2);
868
+ * // Logs: "Processing: 42"
869
+ * // Returns: Ok(84)
870
+ *
871
+ * // Err - tap does nothing
872
+ * ExperimentalResult.Err("fail").tap((x) => console.log(x)); // Err("fail")
873
+ * ```
874
+ *
875
+ * @see tapAsync
876
+ * @see tapErr
877
+ */
878
+ tap(fn: (val: T) => Promise<void>): never;
879
+ tap(fn: (val: T) => void): ExperimentalResult<T, E>;
880
+ /**
881
+ * Executes an async side effect function for Ok values, then returns self.
882
+ *
883
+ * Same as `tap` but for async side effect functions.
884
+ * Returns `Promise<Result<T, E>>`.
885
+ *
886
+ * @param fn - Async function to execute with the Ok value
887
+ * @returns Promise resolving to the same Result (chainable)
888
+ *
889
+ * @example
890
+ * ```ts
891
+ * await ExperimentalResult.Ok(user)
892
+ * .tapAsync(async (u) => await logAuditTrail(u))
893
+ * .map((u) => u.id);
894
+ * ```
895
+ *
896
+ * @see tap
897
+ */
898
+ tapAsync(fn: (val: T) => Promise<void>): Promise<ExperimentalResult<T, E>>;
899
+ /**
900
+ * Executes a side effect function for Err values, then returns self.
901
+ *
902
+ * Useful for logging errors or executing cleanup without breaking the chain.
903
+ * The function is only called if the Result is Err.
904
+ *
905
+ * For async side effects, use `tapErrAsync` instead.
906
+ *
907
+ * @param fn - Function to execute with the error
908
+ * @returns The same Result (chainable)
909
+ *
910
+ * @example
911
+ * ```ts
912
+ * ExperimentalResult.Err("Connection failed")
913
+ * .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
914
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
915
+ * // Logs error timestamp
916
+ * // Returns: Ok(defaultValue)
917
+ *
918
+ * // Ok - tapErr does nothing
919
+ * ExperimentalResult.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
920
+ * ```
921
+ *
922
+ * @see tapErrAsync
923
+ * @see tap
924
+ */
925
+ tapErr(fn: (err: E) => void): ExperimentalResult<T, E>;
926
+ /**
927
+ * Executes an async side effect function for Err values, then returns self.
928
+ *
929
+ * Same as `tapErr` but for async side effect functions.
930
+ * Returns `Promise<Result<T, E>>`.
931
+ *
932
+ * @param fn - Async function to execute with the error
933
+ * @returns Promise resolving to the same Result (chainable)
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * await ExperimentalResult.Err("API error")
938
+ * .tapErrAsync(async (e) => await reportToSentry(e))
939
+ * .orElse((e) => ExperimentalResult.Ok(backupData));
940
+ * ```
941
+ *
942
+ * @see tapErr
943
+ */
944
+ tapErrAsync(fn: (err: E) => Promise<void>): Promise<ExperimentalResult<T, E>>;
945
+ /**
946
+ * Swaps the Ok and Err states, turning success into failure and vice versa.
947
+ *
948
+ * Useful for inverting the meaning of a Result, such as converting
949
+ * validation errors to successes and valid values to errors.
950
+ *
951
+ * @returns Result<E, T> with swapped states
952
+ *
953
+ * @example
954
+ * ```ts
955
+ * ExperimentalResult.Ok("Success value").flip(); // Err("Success value")
956
+ * ExperimentalResult.Err("Error value").flip(); // Ok("Error value")
957
+ *
958
+ * // Invert validation (fail if value is in blacklist)
959
+ * const blacklist = ["admin", "root"];
960
+ * const isBlacklisted = (name: string) =>
961
+ * ExperimentalResult.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
962
+ * .flip(); // Ok if blacklisted, Err if not
963
+ * ```
964
+ */
965
+ flip(): ExperimentalResult<E, T>;
966
+ /**
967
+ * Converts Result to Option, discarding error information.
968
+ *
969
+ * - Ok(value) → Some(value)
970
+ * - Err(error) → None
971
+ *
972
+ * Use when you only care about presence/absence of a value, not the error.
973
+ *
974
+ * @returns Option<T> - Some if Ok, None if Err
975
+ *
976
+ * @example
977
+ * ```ts
978
+ * ExperimentalResult.Ok(42).toOption(); // Some(42)
979
+ * ExperimentalResult.Err("fail").toOption(); // None
980
+ *
981
+ * // Safe user lookup
982
+ * const userOpt = fetchUser(id).toOption();
983
+ * // User or None, regardless of why fetch failed
984
+ * ```
985
+ *
986
+ * @see Option.toResult
987
+ */
988
+ toOption(): ExperimentalOption<T>;
989
+ /**
990
+ * Maps over array elements inside a Result<Array<T>, E>.
991
+ *
992
+ * Applies the mapper function to each element if the Result is Ok and
993
+ * contains an array. Propagates Err unchanged.
994
+ *
995
+ * @param mapper - Function to map over each array element
996
+ * @returns Result<Array<Out>, E> with mapped array or propagated error
997
+ * @throws Error if the Result is Ok but value is not an array
998
+ *
999
+ * @example
1000
+ * ```ts
1001
+ * ExperimentalResult.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
1002
+ * ExperimentalResult.Err("fail").innerMap((x) => x * 2); // Err("fail")
1003
+ * ```
1004
+ */
1005
+ innerMap<In, E, Out>(this: ExperimentalResult<Array<In>, E>, mapper: (val: NoInfer<In>) => Out): ExperimentalResult<Array<Out>, E>;
1006
+ /**
1007
+ * Makes Result iterable for use with generator-based syntax.
1008
+ * Yields self and returns the unwrapped value when resumed.
1009
+ *
1010
+ * @example
1011
+ * ```ts
1012
+ * const result = ExperimentalResult.gen(function* () {
1013
+ * const value = yield* ExperimentalResult.Ok(42);
1014
+ * return value * 2;
1015
+ * });
1016
+ * ```
1017
+ */
1018
+ [Symbol.iterator](): Generator<ExperimentalResult<T, E>, T, unknown>;
1019
+ /**
1020
+ * Makes Result iterable for use with async generator-based syntax.
1021
+ * Yields self and returns the unwrapped value when resumed.
1022
+ *
1023
+ * @example
1024
+ * ```ts
1025
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1026
+ * const value = yield* ExperimentalResult.Ok(42);
1027
+ * return value * 2;
1028
+ * });
1029
+ * ```
1030
+ */
1031
+ [Symbol.asyncIterator](): AsyncGenerator<ExperimentalResult<T, E>, T, unknown>;
1032
+ /**
1033
+ * Creates an ExperimentalResult from a nullable value.
1034
+ * Returns Err(error) for null/undefined, otherwise Ok(non-null value).
1035
+ */
1036
+ static fromNullable<T, E>(val: T | null | undefined, error: E): ExperimentalResult<NonNullable<T>, E>;
1037
+ /** Create Result based on predicate result */
1038
+ static fromPredicate<T, E>(val: T, pred: (v: T) => boolean, error: E): ExperimentalResult<T, E>;
1039
+ /** Catches sync exceptions */
1040
+ static tryCatch<T, E = unknown>(this: void, fn: () => T, errorMapper?: (e: unknown) => E): ExperimentalResult<T, E>;
1041
+ /** Catches async exceptions - returns Promise<Result<T, E>> */
1042
+ static tryAsyncCatch<T, E = unknown>(this: void, fn: () => Promise<T>, errorMapper?: (e: unknown) => E): Promise<ExperimentalResult<T, E>>;
1043
+ /**
1044
+ * Generator-based syntax for chaining Result operations (simplified, no adapter).
1045
+ * Provides imperative-style code while maintaining functional error handling.
1046
+ *
1047
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1048
+ * recursion to avoid stack overflow on deep chains.
1049
+ *
1050
+ * @example
1051
+ * ```ts
1052
+ * const result = ExperimentalResult.gen(function* () {
1053
+ * const a = yield* ExperimentalResult.Ok(1);
1054
+ * const b = yield* ExperimentalResult.Ok(2);
1055
+ * return a + b;
1056
+ * });
1057
+ * // Result<number, never>
1058
+ * ```
1059
+ */
1060
+ static gen<Eff extends ExperimentalResult<any, any>, T>(this: void, genFn: () => Generator<Eff, T, any>): ExperimentalResult<T, ExtractError<Eff>>;
1061
+ /**
1062
+ * Generator-based syntax for chaining Result operations (with adapter).
1063
+ * Uses an adapter function ($) for improved type inference.
1064
+ *
1065
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1066
+ * recursion to avoid stack overflow on deep chains.
1067
+ *
1068
+ * @example
1069
+ * ```ts
1070
+ * const result = ExperimentalResult.genAdapter(function* ($) {
1071
+ * const a = yield* $(ExperimentalResult.Ok(1));
1072
+ * const b = yield* $(ExperimentalResult.Ok(2));
1073
+ * return a + b;
1074
+ * });
1075
+ * // Result<number, never>
1076
+ * ```
1077
+ */
1078
+ static genAdapter<Eff extends ResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E>(result: ExperimentalResult<A, E>) => ResultYieldWrap<A, E>) => Generator<Eff, T, any>): ExperimentalResult<T, ExtractResultError<Eff>>;
1079
+ /**
1080
+ * Async generator-based syntax for chaining Result operations (simplified, no adapter).
1081
+ * Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
1082
+ *
1083
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1084
+ * recursion to avoid stack overflow on deep chains.
1085
+ *
1086
+ * @example
1087
+ * ```ts
1088
+ * const fetchData = async (
1089
+ * id: number,
1090
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1091
+ * ExperimentalResult.Ok({ id });
1092
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1093
+ * const a = yield* ExperimentalResult.Ok(1);
1094
+ * const dataResult = yield* (await fetchData(a));
1095
+ * return a + dataResult.id;
1096
+ * });
1097
+ * // ExperimentalResult<number, string>
1098
+ * ```
1099
+ */
1100
+ static asyncGen<Eff extends ExperimentalResult<any, any>, T>(this: void, genFn: () => AsyncGenerator<Eff, T, any>): Promise<ExperimentalResult<T, ExtractError<Eff>>>;
1101
+ /**
1102
+ * Async generator-based syntax for chaining Result operations (with adapter).
1103
+ * Uses an adapter function ($) for improved type inference.
1104
+ * Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
1105
+ *
1106
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1107
+ * recursion to avoid stack overflow on deep chains.
1108
+ *
1109
+ * @example
1110
+ * ```ts
1111
+ * const fetchData = async (
1112
+ * id: number,
1113
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1114
+ * ExperimentalResult.Ok({ id });
1115
+ * const result = await ExperimentalResult.asyncGenAdapter(async function* ($) {
1116
+ * const a = yield* $(ExperimentalResult.Ok(1));
1117
+ * const data = yield* $(fetchData(a));
1118
+ * return a + data.id;
1119
+ * });
1120
+ * // ExperimentalResult<number, string>
1121
+ * ```
1122
+ */
1123
+ static asyncGenAdapter<Eff extends AsyncResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E2>(result: ExperimentalResult<A, E2> | Promise<ExperimentalResult<A, E2>>) => AsyncResultYieldWrap<A, E2>) => AsyncGenerator<Eff, T, any>): Promise<ExperimentalResult<T, ExtractAsyncResultError<Eff>>>;
1124
+ }
1125
+ //#endregion
1126
+ export { CombineResults, ExperimentalResult, UnitResult, UnwrapResult };
1127
+ //# sourceMappingURL=result-experimental.d.mts.map