Created
March 1, 2025 22:33
-
-
Save yazaldefilimone/b1d3749def942013ee5128161837432e to your computer and use it in GitHub Desktop.
Result
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Maybe<T> = T | null; | |
export class Result<T, E extends Error = Error> { | |
private readonly value: Maybe<T>; | |
private readonly error: Maybe<E>; | |
private constructor(value: Maybe<T>, error: Maybe<E>) { | |
this.value = value; | |
this.error = error; | |
} | |
static ok<T>(value: T): Result<T, never> { | |
return new Result<T, never>(value, null); | |
} | |
static err<E extends Error>(error: E): Result<never, E> { | |
return new Result<never, E>(null, error); | |
} | |
isOk(): this is Result<T, never> { | |
return this.error === null; | |
} | |
isErr(): this is Result<never, E> { | |
return this.value === null; | |
} | |
unwrap(): T { | |
if (this.isOk()) return this.value!; | |
throw new Error(`Tried to unwrap an Err: ${this.error!.message}`); | |
} | |
unwrapError(): E { | |
if (this.isErr()) return this.error!; | |
throw new Error("Tried to unwrap an Ok as an Error."); | |
} | |
map<U>(fn: (value: T) => U): Result<U, E> { | |
return this.isOk() ? Result.ok(fn(this.value!)) : Result.err(this.error!); | |
} | |
mapErr<F extends Error>(fn: (error: E) => F): Result<T, F> { | |
return this.isErr() ? Result.err(fn(this.error!)) : Result.ok(this.value!); | |
} | |
match<U>(handlers: { ok: (value: T) => U; err: (error: E) => U }): U { | |
return this.isOk() ? handlers.ok(this.value!) : handlers.err(this.error!); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment