initial commit
This commit is contained in:
56
lib.ts
Normal file
56
lib.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
interface ResultInterface<T, E> {
|
||||
unwrap: () => T | E;
|
||||
readonly success: boolean;
|
||||
}
|
||||
|
||||
export class ResultSuccess<T> implements ResultInterface<T, never> {
|
||||
data: T;
|
||||
readonly success = true;
|
||||
|
||||
constructor(data: T) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
unwrap(): T {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
|
||||
export class ResultError<E> implements ResultInterface<never, E> {
|
||||
error: E;
|
||||
readonly success = false;
|
||||
|
||||
constructor(error: E) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
unwrap(): E {
|
||||
return this.error;
|
||||
}
|
||||
}
|
||||
|
||||
export type Result<T, E> = ResultSuccess<T> | ResultError<E>;
|
||||
|
||||
export function ok<T = undefined>(value?: T): ResultSuccess<T>;
|
||||
export function ok<T>(value: T) {
|
||||
return new ResultSuccess(value);
|
||||
}
|
||||
|
||||
export function fail<T = undefined>(error?: T): ResultError<T>;
|
||||
export function fail<T>(error: T) {
|
||||
return new ResultError(error);
|
||||
}
|
||||
|
||||
export function fromPromise<T>(
|
||||
promise: Promise<T>,
|
||||
): Promise<Result<T, unknown>> {
|
||||
return promise.then(ok).catch(fail);
|
||||
}
|
||||
|
||||
export function catchThrow<T>(func: () => T): Result<T, unknown> {
|
||||
try {
|
||||
return ok(func());
|
||||
} catch (error) {
|
||||
return fail(error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user