typescriptfunctional-programmingpattern-matchingoption-type

Would an Option or Optional type (Option<T>) make sense in TypeScript?


Languages like Haskell, Rust, among others, offer a Maybe or Option type. Even in Java, there is a Optional type nowadays.

For simplicity, I will call this type an 'Option type' in the remaining question. 'Optional type' is apparently often used to describe situations where providing type annotations is optional.

I am curious about the following: does an Option type make sense in a language like TypeScript? The advantages of the Option type are quite convincing in other languages and I find myself missing the type when programming in TypeScript.

Basically, the type system forces you to explicitly unwrap any value that may be inside an Option value. Yes, TypeScript's strict null-checking can also accomplish that, however, working with the Option type offers you an (in my opinion) much nicer way to handle potential None values by providing map(f: T -> U): Option<U> and mapOr(f: T -> U, or: U): Option<U> methods, etc.

For instance, I would like something like the following code to work:

interface Foo {
    member: Option<string>
}
const opt: Option<Foo> = // ... some initialization
const memberLength: number = opt
    .map(x => x.member) // None if x is None, else Some(...)
    .map(x => x.length) // None if x.member is None, else Some(x.length)
    .unwrapOrElse(() => 0);

This is, of course a very simple example, where using an Option type is a bit over-engineered. It should give a basic idea, though.

I currently don't see a reason why this would be a bad idea, but no one seems to have implemented it, as far as I can tell. Would this have a serious performance impact? Or are there any other issues I can't see that make this non-viable?

Note: I am not (mainly) asking for how to implement this (although that is also an interesting topic -- but I have ideas for that). My main concern is finding out why no one seems to be using something like this yet.


Solution

  • EDIT 2023

    use: effect

    EDIT 2019

    Check fp-ts

    Original Answer

    I was missing it coming from Scala (and some Haskell) so I made my own lib for it (and a couple others): MM (MIT license)

    Feel free to hack, fork etc...; it is MIT licensed