Skip to content

Commit 0bdc72d

Browse files
authored
Merge pull request #10 from GregOnNet/feature/infer-success-failure
2 parents 643abdf + 24e155f commit 0bdc72d

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/result.ts

+44
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,20 @@ export type ResultValueOf<T> = T extends Result<infer TResultValue>
2929
? TResultValue
3030
: unknown;
3131

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+
3246
/**
3347
* Represents a successful or failed operation
3448
*/
@@ -275,6 +289,36 @@ export class Result<TValue = Unit, TError = string> {
275289
return !this.isSuccess;
276290
}
277291

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+
278322
/**
279323
* The internal state of the Result
280324
*/

test/result/result.spec.ts

+22
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,28 @@ describe('Result', () => {
4242
});
4343
});
4444

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+
4567
describe('successIf', () => {
4668
describe('condition', () => {
4769
test('creates a successful Result if the condition is true', () => {

0 commit comments

Comments
 (0)