Shulk
Introduction Get startedBasics
Tagged unions Pattern matchingMonads
Result Maybe LoadingAsync
Procedure ConcurrentlyOthers
WrappersPattern matching
Why: Every execution path should be handled
In addition to being syntactically disgraceful, TypeScript switch/case
statements are not safe, as the TypeScript compiler will not let you know that you forgot to handle some execution paths.
This can cause errors, or even mistakes in your business logic.
The solution: use the match function
You can use the match
expression to return a certain value or execute a certain function when the input matches a certain value.
When using match
, the compiler will force you to be exhaustive, reducing chances that your code has unpredictable behaviors, making it way safer.
Let’s take a look at a simple example:
Note that you don’t have to write a specific path for every value.
Every value must be handled one way or another, but you can use _otherwise
to handle all the other cases in the same way.
Now, let’s try to execute lambdas, by using the case
method:
Match numbers
When matching numbers, you can create a case for a specific number, but you can also create a case for numbers within a range!
Match unions
You can evaluate unions in a match expression, simply by using the tag of each variant. It will even infer the correct type when using the case
method!