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
- Identifiers and Keywords in TypeScript
- Data types in TypeScript
- Hello World in TypeScript
- Variables in TypeScript
- TypeScript class
- Classes in TypeScript
- TypeScript Arrays
- TypeScript Tuples
- TypeScript Ambients Declaration
- TypeScript String
- TypeScript Accessor
- Why use Question mark in TypeScript variable ?
- What are the differences between any vs Object in TypeScript?
- How to execute TypeScript file using command line?
- What is the difference between interface and type in TypeScript ?
- How to Import another TypeScript Files ?
- Difference between private keyword and private fields in TypeScript
- What is the difference between 'String' and 'string' in TypeScript ?
- How to Cast a JSON Object Inside of TypeScript Class ?