Last active
May 29, 2018 18:22
-
-
Save lukaszx0/dabd375a60a336c44948b0e71ee70bc6 to your computer and use it in GitHub Desktop.
type script optionals
This file contains 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
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