|
1 | 1 | /** |
2 | 2 | * Represents a result that can be either a value or some errors. |
3 | 3 | */ |
4 | | -export class ValueResult<TValue> { |
| 4 | +export class ValueResult<TValue, TError> { |
5 | 5 | private constructor( |
6 | | - private readonly errorMsgs: string[], |
| 6 | + private readonly errs: TError[], |
7 | 7 | private readonly val?: TValue, |
8 | 8 | ) {} |
9 | 9 |
|
10 | | - public static ok<TValue>(value: TValue): ValueResult<TValue> { |
| 10 | + public static ok<TValue, TError>(value: TValue): ValueResult<TValue, TError> { |
11 | 11 | if (value === undefined) { |
12 | 12 | throw new Error("Value must be set for successful result"); |
13 | 13 | } |
14 | 14 |
|
15 | 15 | return new ValueResult([], value); |
16 | 16 | } |
17 | 17 |
|
18 | | - public static fail<TValue>(errorMsgs: string[]): ValueResult<TValue> { |
19 | | - if (errorMsgs.length === 0) { |
20 | | - throw new Error( |
21 | | - "At least one error message must be set for a failed result", |
22 | | - ); |
| 18 | + public static fail<TValue, TError>( |
| 19 | + errors: TError[], |
| 20 | + ): ValueResult<TValue, TError> { |
| 21 | + if (errors.length === 0) { |
| 22 | + throw new Error("At least one error must be set for a failed result"); |
23 | 23 | } |
24 | 24 |
|
25 | | - return new ValueResult<TValue>(errorMsgs, undefined); |
| 25 | + return new ValueResult<TValue, TError>(errors, undefined); |
26 | 26 | } |
27 | 27 |
|
28 | 28 | public get isOk(): boolean { |
29 | | - return this.errorMsgs.length === 0; |
| 29 | + return this.errs.length === 0; |
30 | 30 | } |
31 | 31 |
|
32 | 32 | public get isFailure(): boolean { |
33 | | - return this.errorMsgs.length > 0; |
| 33 | + return this.errs.length > 0; |
34 | 34 | } |
35 | 35 |
|
36 | | - public get errors(): string[] { |
37 | | - if (!this.errorMsgs) { |
| 36 | + public get errors(): TError[] { |
| 37 | + if (!this.errs) { |
38 | 38 | throw new Error("Cannot get error for successful result"); |
39 | 39 | } |
40 | 40 |
|
41 | | - return this.errorMsgs; |
| 41 | + return this.errs; |
42 | 42 | } |
43 | 43 |
|
44 | 44 | public get value(): TValue { |
|
0 commit comments