Of all languages, TypeScript is far from being the one with the worst null implementation, even if it still is evaluated as an “object”.
You will never get a NullPointerException, but it won’t always make your code safer, as you’re not forced to handle it explicitely in some situations.
The solution: Use the Maybe monad
The Maybe monad is a generic type (and an union under the hood) which can has 2 states: Some (with a value attached), and None (with no value attached).
Type definition
Constructors
Some
None
Methods
map
The map method allows you to map the value contained to another value.
flatMap
The flatMap method allows you to map the value contained to another Maybe.
filter
The filter method allows you to map the value contained to an empty Maybe if a condition is not met.
filterType
The filterType method allows you to map the value contained to an empty Maybe if a condition is not met, while narrowing down its type.
toResult
The toResult method allows you the Maybe to a Result.
Pattern matching
Maybe is an union, which means you can handle it with match.
Examples
Let’s take a divide function that will return no value when confronted to a division by 0: