TypeScript UnionIn TypeScript, we can define a variable that can have multiple types of values. In other words, TypeScript has the ability to combine one or two different types of data (i.e., number, string, etc.). This 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 achieved by using the pipe ('|') symbol between the types. SyntaxExampleOutput: Numeric value of the value: 120 String value of the value: Welcome to JavaTpoint Passing Union Type in Function ParameterWe can pass union type in function as a parameter. It can be shown below. ExampleOutput: Numeric value of the value: 120 String value of the value: Welcome to JavaTpoint Passing Union Type to ArraysWe can also pass union type to an array. It can be shown below. ExampleOutput: Numeric type array: 1 2 3 4 String type array: India America England Union can Replace enumsEnums are used to create types that contain a list of constants. By default, enums have index values (0, 1 ,2, 3, etc.). Enums can be shown 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
|