tsoption
Correct, easy to use Option type for TypeScript. Like Scala options; see the introductory blog post.
Installation
# Using Yarn: yarn add tsoption # Or, using NPM: npm install tsoption --save
Usage
Note: You can use JavaScript instead of TypeScript, but it's not as fun.
.flatMapSome.of5 // Some<number>(5) .map'a' // Some<string>('a') .orElseOption.of'b' // Some<string>('a') (non-string type gives a compile error) .getOrElse'c' // 'a' .flatMapnew None // None<string>() (flatMap can map to any type) .orElseOption.of'b' // Some<string>('b') (non-string type gives a compile error) .get // 'b'
API
Note: The types of each of the expressions below are known at compile time.
// Create an optionOption.of3 // Some(3)Option.of'abc' // Some('abc')Option.ofnull // None (for convenience)Option.ofundefined // None (for convenience)Some.of3 // Some(3)Some.ofnull // Some(null)new Some // Some([1, 2, 3])new None // None // #flatMapSome.of3.flatMapSome.of_ * 2 // Some(6)None.of.flatMapSome.of2 // None // #getSome.of3.get // 3None.of.get // COMPILE ERROR! Can't call get() on None // #getOrElseSome.of1.getOrElse2 // 1None.of.getOrElse2 // 2 // #isEmptySome.of2.isEmpty // false (known at compile time too!)None.of.isEmpty // true (known at compile time too!) // #mapSome.of2.map_ * 2 // Some(4)None.of.map2 // None (known at compile time too!) // #nonEmptySome.of2.nonEmpty // true (known at compile time too!)None.of.nonEmpty // false (known at compile time too!) // #orElseSome.of2.orElseOption.of3 // Some(2)None.of.orElseOption.of3 // Some(3) // #toStringSome.of2.toString // "Some(2)"None.of.toString // "None"
Fantasyland
TSOption is Fantasyland-compliant. It implements:
Fantasyland-Compatible API
// Create an optionOption3 // Some(3)Option'abc' // Some('abc')Optionnull // NoneOptionundefined // None // #chainOption3Option_ * 2 // Some(6)OptionnullOption2 // None (known at compile time too!) // #mapOption2_ * 2 // Some(4)Optionnull2 // None (known at compile time too!) // #apOption2Option_ * 2 // Some(4)OptionnullOption2 // None (known at compile time too!)
Tests
npm test
License
MIT