Gently return errors instead of rudely throwing them using Result<T, E>
Creating a Result<T, E> instance
To create a Result, use the Ok() and Err() functions.
You’ll generally want to create Result<T, E> instances inside functions and return them, like so:
TypeScript successfully infers all of our return types when using packed enums, so no need to pass generics!
Using a Result<T, E> instance
Now let’s assume that the percent() function we just created is part of a library and we want to use it in our code:
Notice that despite half containing an Ok result and double containing an Err result, they still have the same type.
match(): Verbose but exhaustive
To get our value out of the Result, we can use match():
When our Err is an enum, like it is here, we can nest match statements to handle the full chain:
unwrap(): Terse, but explosive
A simpler, but unsafe way of extracting the value is to use the unwrap() function:
Really simple, right? Why deal with all the extra code and overhead of that matching nonsense when you can just unwrap your value like a present?
Well, the problem is that this present might throw a grenade at you when you open it:
You should only use unwrap() if you’re absolutely, positively sure that the function will not return an Err, and it’s best saved for prototyping, after which you can replace them with match() and or() statements to make them safer.
Avoid unwrap() in production.
or(): A solid middle ground
or() is the exact same as unwrap(), except that instead of crashing your program when it encounters an Err it’ll return the fallback value you pass into it: