Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/core/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
export type Ok<T> = [null, T];
export type Error<E> = [E, null];
export type Result<T, E> = Ok<T> | Error<E>;

/**
* A type predicate for the Error type
* ```ts
* if (isError(result)) {
* // can safely call `getError(result)` here
* } else {
* // can safely call `getValue(result)` here
* }
* ```
*/
export function isError<E>(input: Result<unknown, E>): input is Error<E> {
return input[1] === null;
}

export function getValue<T>(input: Ok<T>): T {
return input[1];
}

export function getError<E>(input: Error<E>): E {
return input[0];
}

/**
* Returns the value of a result, or throws the error if present.
*/
export function unsafeUnwrap<T>(input: Result<T, unknown>): T {
if (isError(input)) {
throw getError(input);
}
return getValue(input);
}

export function ok<T>(value: T): Ok<T> {
return [null, value];
}

export function error<E>(error: E): Error<E> {
return [error, null];
}