Skip to content

Instantly share code, notes, and snippets.

@rzane
Created March 8, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rzane/a1984cd2ae70e9740dfe640418b227b9 to your computer and use it in GitHub Desktop.
Save rzane/a1984cd2ae70e9740dfe640418b227b9 to your computer and use it in GitHub Desktop.
The simplest possible `maybe` implementation in TypeScript
type None = null | undefined;
export class Maybe<T> {
private _value: T | undefined;
public constructor(value: T | None) {
this._value = value === null ? undefined : value;
}
public value(): T | undefined {
return this._value;
}
public map<U>(fn: (value: T) => U | None): Maybe<U> {
return new Maybe<U>(typeof value === 'undefined' ? undefined : fn(this._value));
}
}
export const maybe = <T>(value: T | None) => new Maybe<T>(value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment