diff --git a/src/util.ts b/src/util.ts index 327fce0c7..fc11b86b2 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1292,3 +1292,33 @@ export function joinAtMost( return array.join(separator); } + +type Success = Result; +type Failure = Result; + +export class Result { + private constructor( + private readonly _ok: boolean, + public readonly value: T | E, + ) {} + + static ok(value: T): Success { + return new Result(true, value) as Success; + } + + static error(error: E): Failure { + return new Result(false, error) as Failure; + } + + isOk(): this is Success { + return this._ok; + } + + isError(): this is Failure { + return !this._ok; + } + + orElse(defaultValue: T): T { + return this._ok ? (this.value as T) : defaultValue; + } +}