Skip to content

Instantly share code, notes, and snippets.

@maddymanu
Created May 2, 2020 19:24
Show Gist options
  • Select an option

  • Save maddymanu/dea0794bcfd29e2d6773499002342ced to your computer and use it in GitHub Desktop.

Select an option

Save maddymanu/dea0794bcfd29e2d6773499002342ced to your computer and use it in GitHub Desktop.
Practical Example of Unions
// Practical example
//https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
console.log(padLeft('hello', 'world')); //'worldhello'
console.log(padLeft('hello', 10)); // hello
// console.log(padLeft('hello', true)); //Fails to compile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment