fully-optional
Reasoning
When dealing with nullability in Typescript you need to create a union type T | undefined
and then rely on Typescript control flow analysis to make sure you don't use undefined where you want something else
However this approach has its flaws:
- The code is imperative, you do not immediately see the business logic or data manipulation
- The code can quickly become a mess when you nest if statements or check multiple values for null
; declare ; declare ;
Default approach
;
Using fully-optional
;; ;
This library provides an abstraction over manual handling of null values with a concise and composable API
There are, however, other approaches to solve null problem with composability in mind: Maybe
or Option
monads.
So why should you use fully-optional
instead of a Maybe monad?
-
When using Maybes you introduce a new wrapper datatype that does not integrate well into an existing javascript ecosystem
-
There is no need to introduce a new way to handle null values when we have a good standart solution with union types
-
Union types scale better than Maybe monad.
For example you have a function
declare ;When you refactor it's type to
declare ;You will break all the callers of this function, but you will not break them by changing the return type from
T | undefined
toT
Install
npm install fully-optional
yarn add fully-optional
Usage
; declare ; binda, parseInt; // inferred type number | undefined
All functions are also curried data-last to allow composition
;; ; declare ; ; // inferred type number | undefined
API
all
Apply a function to an array of values if all of them are not null or undefined
declare ; allarr,parseInts * n; // number | undefined
bind
Apply a function to a value if it is not null or undefined
declare ; binda,e.toUpperCase; // string | undefined
isEmpty
Check if value is null or undefined
isEmptya;
isNotEmpty
Check if value is not null or undefined
isNotEmptya;
match
Give two functions to handle both empty and non empty cases
declare ; matcha, ;
withDefault
Return default value if the argument is null or undefined
declare ; withDefaulta, '';
withDefaultLazy
Calculate and return default value if the argument is null or undefined
declare ;declare ; withDefaultLazya, expensiveDefaultValue;
Contributing
Pull requests are welcome.
Please make sure to update tests as appropriate.