DEV Community

Cover image for Union Type in TypeScript
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Union Type in TypeScript

In TypeScript, the union type allows us to combine two or more types separated by a pipe symbol ('|').Before moving further, some prior knowledge of typescript is required.

Basic Union Type:

Image description

In the above example, we can see that we declared a variable named "id" by using a union type. As we can see now, we can assign either string or number values to that particular variable.

Image description

As we can see above, typescript throws an error if we try to assign a value of some other type; in our case, we are trying to assign a boolean value to "id," which is not possible because we declared "id" as the union type of string and number.

Union Type as an argument to a function:

Image description

As we can see above, the function myId takes "id" as an argument, which is a union type of string and number.

Image description

In the above example, we can see that typescript throws an error when we try to pass a boolean type as a parameter to the myId function.

Arrays with a union type:

Image description

As we see above, "id" is declared as an array with a union type of string and number.

Image description

When we try to add a boolean type to an array with a union type of string and number, typescript throws an error. 

Union type as type aliases:

Image description

If we take a closer look at the above example, we can see that we are using myIds as a type alias. Type aliases are most useful when you want to chain many data types. As we see above, we are defining argument "id" using a type alias myIds.

Top comments (0)