Maybe is a type to help to work with nullable or undefined types more pleasurable. Very inspired by Haskell and some bits of Rust's pattern matching.
The Maybe
type describes a nullable
or undefined
for a generic type T
. Maybe
types can be built using helper functions.
An enum
type carrying the two kinds of Maybe
values.
Describes data as null
or undefined
.
Describes the data has some value (means data != (undefined || null)
).
Creates a new Maybe<T>
(see examples below).
The ensure
function guarantee to return a value (see examples below).
Respectively validates if a Maybe<T>
is of Some
type or Nada
type.
// Describing a type that hosts some Maybe<T> props
type DataX = {
a: string;
b: number;
c?: string;
d: Maybe<string>;
e: Maybe<string>;
};
// A new data of DataX
const data: DataX = {
a: "1",
b: 2,
d: Some("xpto"), // Should be Some or Nada
e: Nada(), // Should be Some or Nada
};
data.a; // '1'
data.b; // 2
data.c; // undefined
data.d; // { type: '__maybe__some__', value: 'xpto' }
data.e; // { type: '__maybe__nada__' }
// creating a new maybe type
const c = maybe(data.c);
// displaying some values using the `ensure` function.
ensure(c, "nothing defined in c"); // 'nothing defined in c'
ensure(data.d, "nothing defined"); // 'xpto'
ensure(data.e, "nothing defined in e"); // 'nothing defined in e'
// checking if a maybe is some or nada
isSome(data.d) // true
isNada(data.d) // false
isSome(data.e) // false
isNada(data.e) // true
MIT