It’s an established pattern for error handling that came from functional programming and making its way to mainstream languages (Rust has it, C++ is getting it as I linked in my introduction post). But perhaps you had something else in mind?
Here’s a couple of refs to drive the point:
The option
module provides the first alternative to exceptions. The 'a option
data type represents either data of type 'a
- for instance, Some 42
is of type int option
- or the absence of data due to any error as None
.
The Maybe
type encapsulates an optional value. A value of type Maybe
a either contains a value of type a
(represented as Just
a), or it is empty (represented as Nothing
). Using Maybe
is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error
.
To be fair, I played with the C++ implementation since I posted and I found the implementation a little bit “clunky”. Still, I think it’s nice tool to have in your toolbox.
Here’s how you can define Option and Result types in TypeScript
Option
may contain a value. To access the value, you are forced to “unwrap” this container at which point you’ll have “something” with a value or “nothing”.
interface None {
readonly kind: 'None';
}
interface Some<A> {
readonly kind: 'Some';
readonly val: A;
}
type Option<A> = None | Some<A>;
Result
may contain a value (of type A
), and if not it provides an error with a value of type B
(rather than “nothing”)
interface Err<T> {
readonly kind: 'Err';
readonly val: T;
}
interface Ok<T> {
readonly kind: 'Ok';
readonly val: T;
}
type Result<A, B> = Err<A> | Ok<B>;
These are not convential types in TypeScript btw, but the type system is flexible enough to allow expressing them.
Without having generic types (in the “generics” sens), it sounds like a deadend though.
For the interest of the discussion, I’ll note that Kotlin also has a Result type (with its own twist on things), but no Option type : Result - Kotlin Programming Language