Skip to content

Instantly share code, notes, and snippets.

@lukaszx0
Last active May 29, 2018 18:22
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 lukaszx0/dabd375a60a336c44948b0e71ee70bc6 to your computer and use it in GitHub Desktop.
Save lukaszx0/dabd375a60a336c44948b0e71ee70bc6 to your computer and use it in GitHub Desktop.
type script optionals
export declare type Optional<T> = T | undefined;
export function getOptional<T>(optional: Optional<T>, defaultVal?: T): T {
if (optional) {
return <T>optional;
}
if (defaultVal != undefined) {
return defaultVal;
}
throw new Error("the value of optional is undefined");
}
const foo: string | undefined = "foo";
console.log(getOptional(foo)); // => "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment