File tree 2 files changed +66
-0
lines changed
2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change @@ -29,6 +29,20 @@ export type ResultValueOf<T> = T extends Result<infer TResultValue>
29
29
? TResultValue
30
30
: unknown ;
31
31
32
+ /**
33
+ * Represents a successful Result operation.
34
+ */
35
+ type ResultSuccess < TValue > = Result < TValue > & {
36
+ value : TValue ;
37
+ } ;
38
+
39
+ /**
40
+ * Represents a failed Result operation.
41
+ */
42
+ type ResultFailure < TValue , TError > = Result < TValue > & {
43
+ error : TError ;
44
+ } ;
45
+
32
46
/**
33
47
* Represents a successful or failed operation
34
48
*/
@@ -275,6 +289,36 @@ export class Result<TValue = Unit, TError = string> {
275
289
return ! this . isSuccess ;
276
290
}
277
291
292
+ /**
293
+ * Yields value if the result operation succeeded.
294
+ * Hint: Use hasValue() upfront to be sure that result operation succeeded.
295
+ */
296
+ protected get value ( ) {
297
+ return this . state . value ;
298
+ }
299
+
300
+ /**
301
+ * Yields error if the result operation failed.
302
+ * Hint: Use hasError() upfront to be sure that result operation failed.
303
+ */
304
+ protected get error ( ) {
305
+ return this . state . error ;
306
+ }
307
+
308
+ /**
309
+ * Checks if result operation succeeded.
310
+ */
311
+ hasValue ( ) : this is ResultSuccess < TValue > {
312
+ return this . isSuccess ;
313
+ }
314
+
315
+ /**
316
+ * Checks if result operation failed.
317
+ */
318
+ hasError ( ) : this is ResultFailure < TValue , TError > {
319
+ return ! this . isSuccess ;
320
+ }
321
+
278
322
/**
279
323
* The internal state of the Result
280
324
*/
Original file line number Diff line number Diff line change @@ -42,6 +42,28 @@ describe('Result', () => {
42
42
} ) ;
43
43
} ) ;
44
44
45
+ describe ( 'hasValue' , ( ) => {
46
+ test ( 'grants access to value when Result is in success state' , ( ) => {
47
+ const value = 'Alan Turing' ;
48
+ const sut = Result . success ( value ) ;
49
+
50
+ if ( sut . hasValue ( ) ) {
51
+ expect ( sut . value ) . toBe ( value ) ;
52
+ }
53
+ } ) ;
54
+ } ) ;
55
+
56
+ describe ( 'hasError' , ( ) => {
57
+ test ( 'grants access to error when Result is in error state' , ( ) => {
58
+ const error = 'Ouch!' ;
59
+ const sut = Result . failure ( error ) ;
60
+
61
+ if ( sut . hasError ( ) ) {
62
+ expect ( sut . error ) . toBe ( error ) ;
63
+ }
64
+ } ) ;
65
+ } ) ;
66
+
45
67
describe ( 'successIf' , ( ) => {
46
68
describe ( 'condition' , ( ) => {
47
69
test ( 'creates a successful Result if the condition is true' , ( ) => {
You can’t perform that action at this time.
0 commit comments