option-t

Types and implementations whose APIs are inspired by Rust's `Option<T>` and `Result<T, E>`.

Usage no npm install needed!

<script type="module">
  import optionT from 'https://cdn.skypack.dev/option-t';
</script>

README

option-t

npm CI Status (GitHub Actions)

  • This library represents Option type in ECMAScript.
    • You can sort the "nullable" convention in your project.
  • APIs are inspired by Rust Language's Option<T> and Result<T, E>.
  • TypeScript friendly APIs.
    • We recommend to use this with some static type systems like TypeScript.
  • Zero dependency.
  • Tree shakable completely.
  • ES Module compatbile.
    • Support Node.js' ES Module.
    • Of course, we provides CommonJS.

Motivation

This library provides these conventions for your project:

  1. Uniform an expression of "none" value in JavaScript
  2. Uniform a way to carry error information instead of throwing an error.
  3. Provide a utility function to handle 1 and 2 easily.

And Rust's std::option and std::result are suggestive to achieve these conventions in practice. Thus this package is inspired by their design.

Uniform the expression of "none" value.

In JavaScript world, there are many ways to express "there is no value". At least in ECMA262, There are some ways to represent them:

  • undefined (e.g. Map.prototype.get())
  • null (e.g. RegExp.prototype.exec())
  • -1 (e.g. String.prototype.indexOf())

In addition, ECMA262 interacts with DOM binding, Node.js standard modules, and others. There are additional various ways to represent "none" value.

In practice, we write some glue code to tame their various ways in our project to uniform their expression style. This library contributes to uniform the convention to write it.

Uniform the way to carry error information instead of throwing an error.

Exception is useful but it has some terrible aspects. It's easy that try-catch statement be a jump instruction by large scoped try-catch statement. It's hard to find where to throw an error, it's also hard to handle a penetrated exception from a lower layer. Especially, exception mechanism mis-matches with an async programming model. ECMA262 7th' async-await relaxes the problem about an exception with async programming, but there is still the problem about exceptions in traditional synchronous programming. Furthermore, if you interact with setTimeout() and other async APIs built with callback style on event loop, this problem faces you.

And some async-push based paradigm like Rx.Observable<T> does not allow throw any exceptions in their Observable stream. If you throw an error in it, only catch() operator can catch the error. But a programmer would sometimes forget to use its operator. This means that throwing an Error in Rx's Observable is pretty mis-matched action. Promise also has a similar problem.

And exception in ECMA262 is not friendly with static typing model because ECMA262's throw can throw not only Error but also other object types.

In Rust which is a programming language designed for parallel and seftiness, it treats errors in two category:

Rust groups errors into two major categories: recoverable and unrecoverable errors. For a recoverable error, such as a file not found error, it’s reasonable to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, like trying to access a location beyond the end of an array.

This categorization is pretty useful to relax the problem about exception in ECMA262 which this section described.

Thus this library provides a way to express recoverable error and also recommends to use throwing an error only if you intend to throw an unrecoverable error. This categorization introduces a convenient convention for you:

  • If the code uses throw, you should be careful about unrecoverable error.
  • If the code returns Result<T, E> provided this library, then you should handle it correctly.

This convention is clear as error handling style and it's static typing friendly by generics.

Provide a utility function to handle these uniformed expression easily.

Some static type checking tools also provide a way to check nullability and provide these conventions.

Flowtype and TypeScript checks with their control flow analysis (Sorry, I'm not sure about the details of Google Closure Compiler's behavior).

However, these compilers do not provide a way to handle their value easily like map or flatMap operations.

Rust's std::option and std::result have some utilities operation method to handle them easily. This library also provides a convenient way to handle them and its way is inspired by Rust's ones.

Installation

npm install --save option-t
// or
yarn add option-t --save

Usage & APIs

Utility functions for some types.

These are designed for more tree shaking friendly and more usable for JavaScript common world.

We recommend to use these in almost case.

Nullable<T> (T | null)

This can express a value of T type or null.

Undefinable<T> (T | undefined)

This can express a value of T type or undefined.

Maybe<T> (T | null | undefined)

This can express a value of T type, null, or undefined.

Option<T> ({ ok: true; val: T } | { ok: false; })

This can express that there is some values or none as a plain object. This does not have any property method on its prototype. But this allows no including unused methods of them.

Result<T, E> ({ ok: true; val: T } | { ok: false; err: E; })

This can express that there is some values or some error information as a plain object. This does not have any property method on its prototype. But this allows no including unused methods of them.

Wrapper objects (deprecated)

See this guide.

How to import

You can use these paths.

This package provides some sub directories to import various functions (e.g. option-t/PlainResult). Each of them includes the same directory hierarchy with under src/.

If your toolchain does not support exports field in package.json...

For example,

  • If your project uses TypeScript moduleResolution=node.
  • If your project uses a classic bundler which does not support exports field.

you need to use these paths

  • option-t/cjs
    • This directory provides only commonjs style modules.
  • option-t/esm
    • This directory privides only ES Modules.
  • option-t/lib (Deprecated)
    • This directory provides both of an ES module and a commonjs style module.
    • This directory is provided for a bit of a tricky purpose.
      • For example, your project distributes a bundled file with some module bundlers that can handle ES module (e.g. rollup or webpack), But your project also use babel or TypeScript compiler's downlevel transform to transform your code from ES module to Commonjs and your project runs unit-tests for transformed code with plain Node.js which only use require().
    • Please don't use this path if you don't have to use this.
      • After Node.js v13.2, we recommend to use ES Module supported natively.
    • ⚠️ This will be removed in the future major release (tracking issue is #808).
      • If you're using this, please migrate by following steps.
        • option-t/lib/Option: Use option-t/esm/Option or option-t/cjs/Option.
        • option-t/lib/Result: Use option-t/esm/Result or option-t/cjs/Result.
        • Otherwise, replase option-t/lib/*** to option-t/**.

Idioms

  • You can see some idioms of this library for the interoperability to JavaScript world.

See also

These documents would provide more information about Option<T> and Result<T, E>. These are written for Rust, but the essence is just same.

License

MIT License

Contribution

  • Use yarn to install dev-dependency toolchains.