I was looking at a great talk on Functional TypeScript by Thiago Temple in which he goes over a use-case (and general reason) for not using null
whenever possible, but instead enforcing stricter type-checking to cater for empty return types in a homogenous manner.
A value of null
can have any number of meanings, including but not limited to:
- Value not found
- An error has occurred
- Unpredicted case
- Value not required
- Value is falsy
null
therefore hides contextual meaning whenever it’s used. Consider the following function:
If null
is returned, then it could mean either of the following:
- the User could not be found
- an Error has occurred
Since null
doesn’t provide clarity, creating an Option
type that unions a generic Some
type and None
type can help to give meaning to the output:
With these types crated, the findUserById
function’s output will indicate that either one of two options are present in the response; a clear value (of type Some
) or no value (of type None
):
Because of the kind
property is shared between the two types, it can be inspected and used for conditional logic:
Links
- TypeScript Talk by Thiago Temple - https://www.youtube.com/watch?v=fhyHgkH0ZEg