Skip to content

Instantly share code, notes, and snippets.

@qwertie
Created August 8, 2018 01:48
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 qwertie/ab428d7108be7b2002d2ea25f44b4991 to your computer and use it in GitHub Desktop.
Save qwertie/ab428d7108be7b2002d2ea25f44b4991 to your computer and use it in GitHub Desktop.
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