Created
August 8, 2018 01:48
-
-
Save qwertie/ab428d7108be7b2002d2ea25f44b4991 to your computer and use it in GitHub Desktop.
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
function whatAmI(thing: string|RegExp|null|number[]|Date) { | |
if (thing instanceof RegExp || typeof thing === "string") { | |
// Here, TypeScript knows that thing is RegExp|string | |
if (typeof thing !== "string") | |
console.log("Ahh, so it's a RegExp: " + thing.toString()); | |
else | |
console.log("It's a string of length " + thing.length); | |
} else { | |
// Here, TypeScript knows that thing is null|number|Date | |
if (thing == null) | |
console.log("Aha! You just gave me a null."); | |
else if (Array.isArray(thing)) | |
console.log("Oh, it's an array of numbers: " + | |
thing.map(n => n.toPrecision(3)).join(", ")); | |
else | |
console.log("So, it's a date in " + thing.getFullYear()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment