38 lines
863 B
TypeScript
38 lines
863 B
TypeScript
export class Result<T, E = Error> {
|
|
private constructor(
|
|
private readonly _isSuccess: boolean,
|
|
private readonly _value?: T,
|
|
private readonly _error?: E
|
|
) {}
|
|
|
|
public static ok<U>(value: U): Result<U, never> {
|
|
return new Result<U, never>(true, value);
|
|
}
|
|
|
|
public static fail<F>(error: F): Result<never, F> {
|
|
return new Result<never, F>(false, undefined, error);
|
|
}
|
|
|
|
public get isSuccess(): boolean {
|
|
return this._isSuccess;
|
|
}
|
|
|
|
public get isFailure(): boolean {
|
|
return !this._isSuccess;
|
|
}
|
|
|
|
public getValue(): T {
|
|
if (!this._isSuccess) {
|
|
throw new Error(`Cannot get value from failed Result: ${this._error}`);
|
|
}
|
|
return this._value as T;
|
|
}
|
|
|
|
public getError(): E {
|
|
if (this._isSuccess) {
|
|
throw new Error("Cannot get error from successful Result");
|
|
}
|
|
return this._error as E;
|
|
}
|
|
}
|