Skip to content

Instantly share code, notes, and snippets.

@flovilmart
Created July 13, 2019 15:20
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 flovilmart/582be4edf74e3336b83f76bbae76b872 to your computer and use it in GitHub Desktop.
Save flovilmart/582be4edf74e3336b83f76bbae76b872 to your computer and use it in GitHub Desktop.
TS: Optionals
class Optional<T> {
private val: T;
private is_none: boolean;
private constructor(value: T, is_none: boolean = false) {
this.val = value;
this.is_none = is_none;
}
static none<U>(): Optional<U> {
return new Optional(undefined, true);
}
static some<T>(value: T) {
return new Optional(value);
}
map<U>(handler: (obj: T) => U): Optional<U> {
if (!this.is_none) {
return Optional.none();
}
return Optional.some(handler(this.val));
}
}
let value = Optional.some("Hello");
let thing = value.map((string) => {
return string + string;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment