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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.