Created
February 24, 2019 15:35
-
-
Save KSXGitHub/c6771a6d910d0e8598086872effb221e to your computer and use it in GitHub Desktop.
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
interface MaybeBase { | |
readonly loaded: boolean | |
} | |
interface Some<X> extends MaybeBase { | |
readonly loaded: true | |
readonly value: X | |
} | |
interface None extends MaybeBase { | |
readonly loaded: false | |
} | |
type Maybe<X> = Some<X> | None | |
const none = (): None => ({ loaded: false }) | |
const some = <X> (x: X): Some<X> => ({ loaded: true, value: x }) | |
function maybe(x: null | undefined): None | |
function maybe<X>(x: X): Some<X> | |
function maybe<X>(x: X): Maybe<X> { | |
return x === undefined || x === null | |
? none() | |
: some(x) | |
} | |
const loaded = <X>(x: Maybe<X>): x is Some<X> => x.loaded | |
const isSome = loaded | |
const isNone = (x: Maybe<any>): x is None => !x.loaded | |
// -------------- | |
const foo = maybe(null) // None | |
const bar = maybe(undefined) // None | |
const baz = maybe(123) // Some<number> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment