1.0.3 • Published 6 years ago
petrhejna-failable v1.0.3
Failable<T, E>
This package is based on this article about pattern matching in Typescript.
This library can be used to replace throwing errors completely.
Usage
yarn add petrhejna-failable
Example usage in declaration:
async function fetch(
url: string,
request: RequestInit
): Promise<Failable<string, ApiCallError>> {
const response = await fetch(url, request);
const result = await response.text();
if (response.status >= 300) {
const apiError = new ApiCallError(`Error with code: ${response.status}`);
return Failable.Error(apiError);
}
return Failable.Ok(result)
}
Now you can do pattern matching:
async function getData(): Promise<string> {
const result = await fetch(...);
return result.match({
Ok: (t: string) => t,
Error: (e: ApiCallError) => 'Request failed.',
});
}
There are also functions:
mapOk
that allows to map value inside theFailable
.mapError
that allows to map error inside theFailable
.