From f4b47e70135900fb6341f0750a612c9b2844eb59 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Fri, 23 Jan 2026 17:51:02 +0000 Subject: [PATCH] Add result type --- src/util.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) 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; + } +}