Created
May 2, 2020 19:24
-
-
Save maddymanu/dea0794bcfd29e2d6773499002342ced to your computer and use it in GitHub Desktop.
Practical Example of Unions
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
| // 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