mobily / ts-belt

🔧 Fast, modern, and practical utility library for FP in TypeScript.
https://mobily.github.io/ts-belt
MIT License
1.08k stars 30 forks source link

Why an Option type instead of `type` | undefined? #87

Open Visual-Dawg opened 11 months ago

Visual-Dawg commented 11 months ago

Hey, this is a question instead of a real issue, but the discussion tab isnt present.

So I am wondering why you use an Option-Type instead of simply using a union type of <provided type> | undefined? Because with the specific type you always need to wrap the value first instead of just using the functions.

I am not saying that one is better than the other, but simply curious :D

Visual-Dawg commented 10 months ago

I looked more into it, as undefined can be a pain so often and found this article.

For v4, would it make sense to convert all Option functions to take value | undefined? This would make it so much easier to work with it

redbar0n commented 6 months ago

probably because Option handles null as well?

Visual-Dawg commented 5 months ago

Then you can just expand the union to x | undefined | null. I asked this question, as the option type has no syntax support.

JUSTIVE commented 5 months ago

It abstracts the absence of a given type T. You could think of it as just an alias for type representation in raw typescript: T|null|undefined, but there's little more about it. An option type(and the functions in the option module) does is lift functions that work with a given type. If there's a function that takes A and then returns B(A->B), O.map will lift this function O\<A> -> O\<B>. Those nulls and undefineds beneath the option type are just implementations of the idea of absence. Of course, just judging by its implementation, option\<T> seems too naive, and meaningless, but the same goes for other types, like result. After all, all those types will be represented in js/ts, a structural type system. They exists because not they encapsulate complex things, it represents mathematic concepts.

BTW, I understand there are some issues with functions that take options as arguments are easy to cause an error, since the type signature says it takes option type(which should be T| null | undefined), but only works properly when it takes undefined(internal representation of true None).