@carbonteq/fp 0.9.1 → 0.11.1

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