Created
December 8, 2018 13:44
-
-
Save shekohex/015d99d06db3a443cf88fa1444d11197 to your computer and use it in GitHub Desktop.
AsyncResult, a Rusty Result in Typescript, for fun.
This file contains 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 class AsyncResult<T, E extends Error = any> { | |
private constructor(private readonly value?: T, private readonly error?: E) {} | |
public static Ok<T, E extends Error>(value: T) { | |
return new AsyncResult<T, E>(value); | |
} | |
public static Err<T, E extends Error>(error: E) { | |
return new AsyncResult<T, E>(undefined, error); | |
} | |
public unwrap(): T { | |
if (this.value && this.error === undefined) { | |
return this.value; | |
} else { | |
// Painc | |
const error = new Error(); | |
error.message = this.error!.message; | |
error.stack = this.error!.stack; | |
error.name = this.error!.name; | |
throw error; | |
} | |
} | |
public isOk(): boolean { | |
return this.value !== undefined; | |
} | |
public isErr(): boolean { | |
return !this.isOk(); | |
} | |
public unwrapOr(value: T): T { | |
if (this.value) { | |
return this.value; | |
} else { | |
return value; | |
} | |
} | |
public unwrapOrElse(fn: () => T) { | |
if (this.value) { | |
return this.value; | |
} else { | |
return fn(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment