What Are Union Types in TypeScript?

By Hemanta Sundaray on 2023-04-12

Imagine you have a function that takes a person's age as input and performs some kind of validation. What's important to remember here is that age can come in different formats - as a string or a number - depending on where it's coming from.

How do you type annotate the age parameter in the function?

You might be tempted to use any type, but it's not the best approach. Instead, we can use union types to handle this situation.

Union Types allow you to define a variable that can have one of several different types. In TypeScript, you can define a union type using the pipe (|) symbol between two or more types.

For example:

type Age = number | string

Here we’ve assigned a type alias named Age to our types separated by a pipe (|).

Now, let’s create a function that makes use of the Age union type for its age parameter.

function validateAge(age: Age): boolean {
  if (typeof age === "number") {
    return age >= 18
  } else {
    return parseInt(age) >= 18

In this example, the validateAge function takes an age parameter of type Age, which can be either a number or a string. Inside the function, we use the typeof operator to check if age is a number or a string, and then we perform the appropriate validation based on its type.

Note that type checking is necessary while using union types as your argument can be of several types.

In summary, union Types in TypeScript allow you to work with variables that can hold different types of values. And you can use type checking techniques like typeof to handle them differently based on their types.

Join the Newsletter