Created
March 8, 2019 16:59
-
-
Save rzane/a1984cd2ae70e9740dfe640418b227b9 to your computer and use it in GitHub Desktop.
The simplest possible `maybe` implementation in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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