Skip to content

Instantly share code, notes, and snippets.

@Hadaward
Created July 21, 2024 15:00
Show Gist options
  • Select an option

  • Save Hadaward/b5ff365cdef27efdb42bae1f4e198bfa to your computer and use it in GitHub Desktop.

Select an option

Save Hadaward/b5ff365cdef27efdb42bae1f4e198bfa to your computer and use it in GitHub Desktop.
/**
* @summary The Result<Ok, Error> interface describes the result of a function that can occur in two different ways, being an error or a positive result.
* @summary The methods in this interface help the developer to better understand the result of the function and then deal with it directly.
* @summary Use ``Ok(value)`` or ``Err(error)`` to instantiate this.
*/
export interface Result<Ok = any, Err = Error> {
isOk(): boolean,
isErr(): boolean,
/**
* @throws "Tried to unwrap an error value but the value is ok." - When you try to unwrap an ok value as error.
*/
unwrapErr(): Err,
/**
* @throws "Tried to unwrap an ok value but the value is an error." - When you try to unwrap an error value as ok.
*/
unwrapOk(): Ok,
unwrap(): Ok | Err,
unwrapOrDefault<T>(defaultValue: T): Ok | T
}
export function Ok<T = any, E = Error>(value: T): Result<T, E> {
return createResult<T, E>({
isOk: true,
value
});
}
export function Err<T = any, E = Error>(value: E): Result<T, E> {
return createResult<T, E>({
isOk: false,
value
});
}
type ResultOptions<T, E> = {
isOk: true,
value: T
} | {
isOk: false,
value: E
};
function createResult<T, E>(options: ResultOptions<T, E>): Result<T, E> {
return Object.freeze({
isOk() {
return options.isOk;
},
isErr() {
return !options.isOk;
},
unwrapErr() {
if (!options.isOk)
return options.value;
throw `Tried to unwrap an error value but the value is ok.`;
},
unwrapOk() {
if (options.isOk)
return options.value;
throw `Tried to unwrap an ok value but the value is an error.`;
},
unwrap() {
return options.value;
},
unwrapOrDefault<T>(defaultValue: T) {
return options.isOk ? options.value : defaultValue;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment