Created
March 27, 2017 18:36
-
-
Save devmobasa/6bf89bad56e3cf0248077c32f7fe06cc to your computer and use it in GitHub Desktop.
Union Types in TypeScript
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 print(text: string | string[]): string { | |
| if (typeof text === 'string') { | |
| return text; | |
| } | |
| // compiler now knows that you can use join | |
| // and that variable type is definitely string[] | |
| return text.join(' '); | |
| } | |
| let x = print('hello text'); | |
| let y = print(['hello', 'text', 'array']); | |
| // let z = print(5); // Error: Argument of type '5' is not assignable to type 'string | string[]' | |
| console.log(x); | |
| console.log(y); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment