For those in search of a Maybe implementation, I once created a solution that may fit your needs.
/**
* An Implementation of Maybe
* focusing on JavaScript simplicity
* serving as a basic abstraction for null/undefined values
*/
export class Maybe<T>{
private _value: T;
/** Determines if it holds Some or None based on the value */
constructor(value: T) {
this._value = value;
}
/** Shortcut method for constructor */
static Some<T>(value: T): Maybe<T> {
if (value === null || value === undefined) {
throw new Error('Value for Some cannot be null or undefined');
}
return new Maybe(value);
};
static None<T>(): Maybe<T> {
return new Maybe(null);
};
get value(): T {
return this._value;
}
get isSome() {
return this._value !== null && this._value !== undefined;
}
get isNone() {
return !this.isSome;
}
map<U>(mapper: (now: T) => U): Maybe<U> {
if (this.isSome) {
return new Maybe(mapper(this._value));
}
else {
return new Maybe(null);
}
}
}
However, personally, I consider it rather unnecessary. It's much easier to simply handle null/undefined
and utilize the valid
property within your objects (refer to https://medium.com/@basarat/null-vs-undefined-in-typescript-land-dc0c7a5f240a)
Additional Information
Furthermore, TypeScript is moving towards providing robust support for nullability, allowing you to specify types like number | null | undefined
. This will prevent scenarios where you mistakenly assign null
to a number, for instance:
let foo:number = null; // Error foo is not nullable