1.0.3 • Published 6 years ago

petrhejna-failable v1.0.3

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

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 the Failable.
  • mapError that allows to map error inside the Failable.
1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago