The TypeScript union has the ability to combine one or two different types of data (i.e., number, string, float, double, etc). It is the most powerful way to express a variable with multiple types. Use pipe (‘|’) symbol to combine two or more data types to achieve Union type.
190 Welcome to TypeScript!
Example: In this example the geeks is of union type, denoted using (string | number). So, we can assign a string or a number to it nothing else is allowed.
Function Parameter as Union Type: We can pass the function as a parameter. In this example, parameter geeks is of union type. You can pass either a string value or a number value otherwise the compiler will give an error.
Array as Union Type: In union type we can also pass an array. The program declares an array. The array can represent either a numeric collection or a string collection.
Display the array elements 2 5 7 5 11 15 Display the array elements Geeks G4G GFG GeeksforGeeks
- Hello World in TypeScript
- Classes in TypeScript
- TypeScript class
- Variables in TypeScript
- TypeScript String
- TypeScript Arrays
- TypeScript Tuples
- TypeScript Accessor
- Data types in TypeScript
- How to Import another TypeScript Files ?
- TypeScript Ambients Declaration
- What are the differences between any vs Object in TypeScript?
- Identifiers and Keywords in TypeScript
- Why use Question mark in TypeScript variable ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.