loading...

re: The Maybe data type in JavaScript VIEW POST

FULL DISCUSSION
 

Using Maybe like that has no sense. If you will use nullable (value | null) then withDefault is just x ?? 0 what means if x is null then fallback to 0. There is no value in Maybe here, only additional abstraction instead of idiomatic construct.

Maybe starts to have sense when you totally work with it in functional way. When u use maps, binds and ap.

If you write statements (and if is a statement) then I would say you don't need Maybe, Nullable is idiomatic and fully ok. If you use TS then compiler will inform you when you need to check if value is there, so win win. Additionally you don't loose latest added feature of optional chaining which works with null values.

But if you go fully functional then many things become harder with idiomatic JS, and then such constructs has a sense.

Below using Nullable.

function divide(numerator, denominator) {
    if (denominator === 0) {
        return null
    }
    return numerator / denominator;
}
// using
const x = divide(1,2) ?? 0

If we would type arguments as numbers then TS would automatically say the function returns number | null and dev would be enforce to or check the value or set the fallback

 

Very good point! Could you please describe when using Maybe make sens in JavaScript/TypeScript?
And also do you know some libraries that provides Maybe types?

 

Will write the whole article about that. So watch out for it :)

code of conduct - report abuse