JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 322
  • Score
    100M100P100Q85806F
  • License MIT

Correct, easy to use Option type for TypeScript

Package Exports

  • tsoption

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (tsoption) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

tsoption Build Status npm mit

Correct, easy to use Option type for TypeScript

Installation

npm i tsoption -S

Usage

Note: You can use JavaScript instead of TypeScript, but it's not as fun.

let a = Option(3)
  .flatMap(_ => Option(5))  // Some(5)
  .map(_ => 'a')            // Some('a')
  .orElse(Option('b'))      // Some('a')   -- non-string type gives a compile error
  .getOrElse('c')           // 'a'

let b = Option('a')         // Some('a')
  .map(() => null)          // None(null)  -- map can map to any type
  .orElse(Option('b'))      // Some('b')   -- non-string type gives a compile error
  .get()                    // 'b'

API

// Create an option
Option(3)                                // Some(3)
Option('abc')                            // Some('abc')
Option(null)                             // None
Option(undefined)                        // None

// #flatMap
Option(3).flatMap(_ => Option(_ * 2))    // Some(6)
Option(null).flatMap(() => Option(2))    // None  (known at compile time too!)

// #get
Option(3).get()                          // 3
Option(null).get()                       // COMPILE ERROR! Can't call get() on None

// #getOrElse
Option(1).getOrElse(2)                   // 1
Option(null).getOrElse(2)                // 2

// #isEmpty
Option(2).isEmpty()                      // false (known at compile time too!)
Option(null).isEmpty()                   // true  (known at compile time too!)

// #map
Option(2).map(_ => _ * 2)                // Option(4)
Option(null).map(() => 2)                // None  (known at compile time too!)

// #nonEmpty
Option(2).nonEmpty()                     // true  (known at compile time too!)
Option(null).nonEmpty()                  // false (known at compile time too!)

// #orElse
Option(2).orElse(Option(3))              // Some(2)
Option(null).orElse(Option(3))           // Some(3)

// #toString
Option(2).toString()                     // "Some(2)"
Option(null).toString()                  // "None"

Tests

npm test

License

MIT