TypeScript UnionIn TypeScript, we can define a variable which can have multiple types of values. In other words, TypeScript can combine one or two different types of data (i.e., number, string, etc.) in a single type, which is called a union type. Union types are a powerful way to express a variable with multiple types. Two or more data types can be combined by using the pipe ('|') symbol between the types. SyntaxExampleOutput: The Numeric value of the value is: 120 The String value of the value is: Welcome to JavaTpoint Passing Union Type in Function ParameterIn function, we can pass a union type as a parameter. We can understand it from the below example. ExampleOutput: The given value is of type number. The given value is of type of string. Passing Union Type to ArraysTypeScript allows passing a union type to an array. We can understand it from the below example. ExampleOutput: Numeric type array: 1 2 3 4 String type array: India America England The union can replace enums.Enums are used to create types that contain a list of constants. By default, enums have index values (0, 1, 2, 3, etc.). We can see the enums in the following example, which contains the list of colors. ExampleInstead of enums, we can use union types and can get similar benefits in a much shorter way. ExampleOutput: RED
Next TopicTypeScript String
|