Skip to content

Instantly share code, notes, and snippets.

@shekohex
Created December 8, 2018 13:44
Show Gist options
  • Save shekohex/015d99d06db3a443cf88fa1444d11197 to your computer and use it in GitHub Desktop.
Save shekohex/015d99d06db3a443cf88fa1444d11197 to your computer and use it in GitHub Desktop.
AsyncResult, a Rusty Result in Typescript, for fun.
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