Last active
July 4, 2019 09:01
-
-
Save aal89/fb8a69a4c29b0c7c71cf1599fcf397e4 to your computer and use it in GitHub Desktop.
Optional class to default out variables when they do not exist.
This file contains hidden or 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
class Optional<T> { | |
private value: T | null = null; | |
private constructor(value: T | null) { | |
this.value = value; | |
} | |
public static some<T>(value: T): Optional<T> { | |
return new Optional(value); | |
} | |
public static none<T>(): Optional<T> { | |
return new Optional(null); | |
} | |
// helper method | |
public static from<T>(value: T): Optional<T> { | |
return value === null ? new Optional(null) : new Optional(value); | |
} | |
public getOr(alternative: T): T { | |
return this.value ? this.value : alternative; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage with an imaginary
IConfig
interface: