Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optional in typecript
export class Optional<T> {
constructor(public value:T) {
}
isPresent():boolean {
return this.value !== null && this.value !== undefined;
}
map(bindCall):Optional<T> {
if (this.isPresent()) {
return Optional.someOrNone(bindCall(this.value));
} else {
return this;
}
}
flatMap(bindCall) {
if (this.isPresent()) {
return bindCall(this.value);
} else {
return this;
}
}
filter(f: (T)=>boolean) {
if (this.isPresent() && f(this.value)) {
return this;
}
// equivalent of return none() without cyclic creation
// eslint : no-use-before-define
return Optional.none();
}
get():T {
if (!this.isPresent()){
throw 'Accessing empty value';
}
return this.value;
}
orElse(value:T):T {
if (this.isPresent()) {
return this.value;
} else {
return value;
}
}
orLazyElse(value:()=>T):T {
if (this.isPresent()) {
return this.value;
} else {
return value();
}
}
static of(value){
return new Optional(value);
}
static none(){
return new Optional(null);
}
static someOrNone(value){
if (value === undefined || value === null){
return Optional.none();
}
return new Optional(value);
}
}
@nicolas-zozol
Copy link
Author

nicolas-zozol commented Sep 12, 2019

Could be improved by using a symbol("empty") instead of null or undefined

@nicolas-zozol
Copy link
Author

nicolas-zozol commented Sep 12, 2019

const findUsers = ()=> return Optional.none()

return findUsers().orElse(johnDoe)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment