Skip to content

Instantly share code, notes, and snippets.

@aal89
Last active July 4, 2019 09:01
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 aal89/fb8a69a4c29b0c7c71cf1599fcf397e4 to your computer and use it in GitHub Desktop.
Save aal89/fb8a69a4c29b0c7c71cf1599fcf397e4 to your computer and use it in GitHub Desktop.
Optional class to default out variables when they do not exist.
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;
}
}
@aal89
Copy link
Author

aal89 commented Jul 4, 2019

Example usage with an imaginary IConfig interface:

class App {

  private config: IConfig;

  constructor(config: Optional<IConfig>) {
    this.config = config.getOr(new DefaultConfig());
  }

}

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