-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathresult.ts
More file actions
503 lines (481 loc) · 18.5 KB
/
result.ts
File metadata and controls
503 lines (481 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/**
* Represents the successful outcome of an operation, encapsulating the success value.
*
* This is the 'Ok' variant of the `Result` type. It holds a `data` property
* of type `T` (the success value) and an `error` property explicitly set to `null`,
* signifying no error occurred.
*
* Use this type in conjunction with `Err<E>` and `Result<T, E>`.
*
* @template T - The type of the success value contained within.
*/
export type Ok<T> = { data: T; error: null };
/**
* Represents the failure outcome of an operation, encapsulating the error value.
*
* This is the 'Err' variant of the `Result` type. It holds an `error` property
* of type `E` (the error value) and a `data` property explicitly set to `null`,
* signifying that no success value is present due to the failure.
*
* Use this type in conjunction with `Ok<T>` and `Result<T, E>`.
*
* @template E - The type of the error value contained within.
*/
export type Err<E> = { error: E; data: null };
/**
* A type that represents the outcome of an operation that can either succeed or fail.
*
* `Result<T, E>` is a discriminated union type with two possible variants:
* - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.
* In this case, the `error` field is `null`.
* - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.
* In this case, the `data` field is `null`.
*
* This type promotes explicit error handling by requiring developers to check
* the variant of the `Result` before accessing its potential value or error.
* It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).
*
* @template T - The type of the success value if the operation is successful (held in `Ok<T>`).
* @template E - The type of the error value if the operation fails (held in `Err<E>`).
* @example
* ```ts
* function divide(numerator: number, denominator: number): Result<number, string> {
* if (denominator === 0) {
* return Err("Cannot divide by zero");
* }
* return Ok(numerator / denominator);
* }
*
* const result1 = divide(10, 2);
* if (isOk(result1)) {
* console.log("Success:", result1.data); // Output: Success: 5
* }
*
* const result2 = divide(10, 0);
* if (isErr(result2)) {
* console.error("Failure:", result2.error); // Output: Failure: Cannot divide by zero
* }
* ```
*/
export type Result<T, E> = Ok<T> | Err<E>;
/**
* Constructs an `Ok<T>` variant, representing a successful outcome.
*
* This factory function creates the success variant of a `Result`.
* It wraps the provided `data` (the success value) and ensures the `error` property is `null`.
*
* @template T - The type of the success value.
* @param data - The success value to be wrapped in the `Ok` variant.
* @returns An `Ok<T>` object with the provided data and `error` set to `null`.
* @example
* ```ts
* const successfulResult = Ok("Operation completed successfully");
* // successfulResult is { data: "Operation completed successfully", error: null }
* ```
*/
export const Ok = <T>(data: T): Ok<T> => ({ data, error: null });
/**
* Constructs an `Err<E>` variant, representing a failure outcome.
*
* This factory function creates the error variant of a `Result`.
* It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
*
* @template E - The type of the error value.
* @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
* @returns An `Err<E>` object with the provided error and `data` set to `null`.
* @example
* ```ts
* const failedResult = Err(new TypeError("Invalid input"));
* // failedResult is { error: TypeError("Invalid input"), data: null }
* ```
*/
export const Err = <E>(error: E): Err<E> => ({ error, data: null });
/**
* Utility type to extract the success value's type `T` from a `Result<T, E>` type.
*
* If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),
* this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.
* This is useful for obtaining the type of the `data` field when you know you have a success.
*
* @template R - The `Result<T, E>` type from which to extract the success value's type.
* Must extend `Result<unknown, unknown>`.
* @example
* ```ts
* type MyResult = Result<number, string>;
* type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number
*
* type MyErrorResult = Err<string>;
* type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never
* ```
*/
export type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>
? U
: never;
/**
* Utility type to extract the error value's type `E` from a `Result<T, E>` type.
*
* If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),
* this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.
* This is useful for obtaining the type of the `error` field when you know you have a failure.
*
* @template R - The `Result<T, E>` type from which to extract the error value's type.
* Must extend `Result<unknown, unknown>`.
* @example
* ```ts
* type MyResult = Result<number, string>;
* type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string
*
* type MySuccessResult = Ok<number>;
* type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never
* ```
*/
export type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<
infer E
>
? E
: never;
/**
* Type guard to runtime check if an unknown value is a valid `Result<T, E>`.
*
* A value is considered a valid `Result` if:
* 1. It is a non-null object.
* 2. It has both `data` and `error` properties.
* 3. At least one of the `data` or `error` channels is `null`. Both being `null` represents `Ok(null)`.
*
* This function does not validate the types of `data` or `error` beyond `null` checks.
*
* @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).
* @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).
* @param value - The value to check.
* @returns `true` if the value conforms to the `Result` structure, `false` otherwise.
* If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.
* @example
* ```ts
* declare const someValue: unknown;
*
* if (isResult<string, Error>(someValue)) {
* // someValue is now typed as Result<string, Error>
* if (isOk(someValue)) {
* console.log(someValue.data); // string
* } else {
* console.error(someValue.error); // Error
* }
* }
* ```
*/
export function isResult<T = unknown, E = unknown>(
value: unknown,
): value is Result<T, E> {
const isNonNullObject = typeof value === "object" && value !== null;
if (!isNonNullObject) return false;
const hasDataProperty = "data" in value;
const hasErrorProperty = "error" in value;
if (!hasDataProperty || !hasErrorProperty) return false;
return true;
}
/**
* Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.
*
* This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.
* An `Ok<T>` variant is identified by its `error` property being `null`.
*
* @template T - The success value type.
* @template E - The error value type.
* @param result - The `Result<T, E>` to check.
* @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.
* If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.
* @example
* ```ts
* declare const myResult: Result<number, string>;
*
* if (isOk(myResult)) {
* // myResult is now typed as Ok<number>
* console.log("Success value:", myResult.data); // myResult.data is number
* }
* ```
*/
export function isOk<T, E>(result: Result<T, E>): result is Ok<T> {
return result.error === null;
}
/**
* Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.
*
* This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.
* An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).
*
* @template T - The success value type.
* @template E - The error value type.
* @param result - The `Result<T, E>` to check.
* @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.
* If `true`, TypeScript's type system will narrow `result` to `Err<E>`.
* @example
* ```ts
* declare const myResult: Result<number, string>;
*
* if (isErr(myResult)) {
* // myResult is now typed as Err<string>
* console.error("Error value:", myResult.error); // myResult.error is string
* }
* ```
*/
export function isErr<T, E>(result: Result<T, E>): result is Err<E> {
return result.error !== null; // Equivalent to result.data === null
}
/**
* Executes a synchronous operation and wraps its outcome in a Result type.
*
* This function attempts to execute the `try` operation:
* - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant.
* - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to
* the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).
*
* The return type is automatically narrowed based on what your catch function returns:
* - If catch always returns `Ok<T>`, the function returns `Ok<T>` (guaranteed success)
* - If catch always returns `Err<E>`, the function returns `Result<T, E>` (may succeed or fail)
* - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Result<T, E>` (conditional recovery)
*
* @template T - The success value type
* @template E - The error value type (when catch can return errors)
* @param options - Configuration object
* @param options.try - The operation to execute
* @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation)
* @returns `Ok<T>` if catch always returns Ok (recovery), otherwise `Result<T, E>` (propagation or conditional recovery)
*
* @example
* ```ts
* // Returns Ok<string> - guaranteed success since catch always returns Ok
* const alwaysOk = trySync({
* try: () => JSON.parse(input),
* catch: () => Ok("fallback") // Always Ok<T>
* });
*
* // Returns Result<object, string> - may fail since catch always returns Err
* const mayFail = trySync({
* try: () => JSON.parse(input),
* catch: (err) => Err("Parse failed") // Returns Err<E>
* });
*
* // Returns Result<void, MyError> - conditional recovery based on error type
* const conditional = trySync({
* try: () => riskyOperation(),
* catch: (err) => {
* if (isRecoverable(err)) return Ok(undefined);
* return MyErr({ message: "Unrecoverable" });
* }
* });
* ```
*/
export function trySync<T>(options: {
try: () => T;
catch: (error: unknown) => Ok<T>;
}): Ok<T>;
export function trySync<T, E>(options: {
try: () => T;
catch: (error: unknown) => Err<E>;
}): Result<T, E>;
export function trySync<T, E>(options: {
try: () => T;
catch: (error: unknown) => Ok<T> | Err<E>;
}): Result<T, E>;
export function trySync<T, E>({
try: operation,
catch: catchFn,
}: {
try: () => T;
catch: (error: unknown) => Ok<T> | Err<E>;
}): Ok<T> | Result<T, E> {
try {
const data = operation();
return Ok(data);
} catch (error) {
return catchFn(error);
}
}
/**
* Executes an asynchronous operation and wraps its outcome in a Promise<Result>.
*
* This function attempts to execute the `try` operation:
* - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
* - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to
* the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).
*
* The return type is automatically narrowed based on what your catch function returns:
* - If catch always returns `Ok<T>`, the function returns `Promise<Ok<T>>` (guaranteed success)
* - If catch always returns `Err<E>`, the function returns `Promise<Result<T, E>>` (may succeed or fail)
* - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Promise<Result<T, E>>` (conditional recovery)
*
* @template T - The success value type
* @template E - The error value type (when catch can return errors)
* @param options - Configuration object
* @param options.try - The async operation to execute
* @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation)
* @returns `Promise<Ok<T>>` if catch always returns Ok (recovery), otherwise `Promise<Result<T, E>>` (propagation or conditional recovery)
*
* @example
* ```ts
* // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok
* const alwaysOk = tryAsync({
* try: async () => fetch(url),
* catch: () => Ok(new Response()) // Always Ok<T>
* });
*
* // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err
* const mayFail = tryAsync({
* try: async () => fetch(url),
* catch: (err) => Err(new Error("Fetch failed")) // Returns Err<E>
* });
*
* // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type
* const conditional = await tryAsync({
* try: async () => {
* await deleteFile(filename);
* },
* catch: (err) => {
* if ((err as { name?: string }).name === 'NotFoundError') {
* return Ok(undefined); // Already deleted, that's fine
* }
* return BlobErr({ message: "Delete failed" });
* }
* });
* ```
*/
export async function tryAsync<T>(options: {
try: () => Promise<T>;
catch: (error: unknown) => Ok<T>;
}): Promise<Ok<T>>;
export async function tryAsync<T, E>(options: {
try: () => Promise<T>;
catch: (error: unknown) => Err<E>;
}): Promise<Result<T, E>>;
export async function tryAsync<T, E>(options: {
try: () => Promise<T>;
catch: (error: unknown) => Ok<T> | Err<E>;
}): Promise<Result<T, E>>;
export async function tryAsync<T, E>({
try: operation,
catch: catchFn,
}: {
try: () => Promise<T>;
catch: (error: unknown) => Ok<T> | Err<E>;
}): Promise<Ok<T> | Result<T, E>> {
try {
const data = await operation();
return Ok(data);
} catch (error) {
return catchFn(error);
}
}
/**
* Resolves a value that may or may not be wrapped in a `Result`, returning the final value.
*
* This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:
* - If `value` is an `Ok<T>` variant, returns the contained success value.
* - If `value` is an `Err<E>` variant, throws the contained error value.
* - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),
* returns it as-is.
*
* This is useful when working with APIs that might return either direct values or Results,
* allowing you to normalize them to the actual value or propagate errors via throwing.
*
* Use `resolve` when the input might or might not be a Result.
* Use `unwrap` when you know the input is definitely a Result.
*
* @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.
* @template E - The type of the error value (if `value` is `Err<E>`).
* @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.
* @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.
* @throws The error value `E` if `value` is an `Err<E>` variant.
*
* @example
* ```ts
* // Example with an Ok variant
* const okResult = Ok("success data");
* const resolved = resolve(okResult); // "success data"
*
* // Example with an Err variant
* const errResult = Err(new Error("failure"));
* try {
* resolve(errResult);
* } catch (e) {
* console.error(e.message); // "failure"
* }
*
* // Example with a plain value
* const plainValue = "plain data";
* const resolved = resolve(plainValue); // "plain data"
*
* // Example with a function that might return Result or plain value
* declare function mightReturnResult(): string | Result<string, Error>;
* const outcome = mightReturnResult();
* try {
* const finalValue = resolve(outcome); // handles both cases
* console.log("Final value:", finalValue);
* } catch (e) {
* console.error("Operation failed:", e);
* }
* ```
*/
/**
* Unwraps a `Result<T, E>`, returning the success value or throwing the error.
*
* This function extracts the data from a `Result`:
* - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.
* - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.
*
* Unlike `resolve`, this function expects the input to always be a `Result` type,
* making it more direct for cases where you know you're working with a `Result`.
*
* @template T - The type of the success value contained in the `Ok<T>` variant.
* @template E - The type of the error value contained in the `Err<E>` variant.
* @param result - The `Result<T, E>` to unwrap.
* @returns The success value of type `T` if the `Result` is `Ok<T>`.
* @throws The error value of type `E` if the `Result` is `Err<E>`.
*
* @example
* ```ts
* // Example with an Ok variant
* const okResult = Ok("success data");
* const value = unwrap(okResult); // "success data"
*
* // Example with an Err variant
* const errResult = Err(new Error("something went wrong"));
* try {
* unwrap(errResult);
* } catch (error) {
* console.error(error.message); // "something went wrong"
* }
*
* // Usage in a function that returns Result
* function divide(a: number, b: number): Result<number, string> {
* if (b === 0) return Err("Division by zero");
* return Ok(a / b);
* }
*
* try {
* const result = unwrap(divide(10, 2)); // 5
* console.log("Result:", result);
* } catch (error) {
* console.error("Division failed:", error);
* }
* ```
*/
export function unwrap<T, E>(result: Result<T, E>): T {
if (isOk(result)) {
return result.data;
}
throw result.error;
}
export function resolve<T, E>(value: T | Result<T, E>): T {
if (isResult<T, E>(value)) {
if (isOk(value)) {
return value.data;
}
// If it's a Result and not Ok, it must be Err.
// The type guard isResult<T,E>(value) and isOk(value) already refine the type.
// So, 'value' here is known to be Err<E>.
throw value.error;
}
// If it's not a Result type, return the value as-is.
// 'value' here is known to be of type T.
return value;
}