Benjamin Semah
Benjamin Semah

Follow

Benjamin Semah

Follow

Union Types in TypeScript

Benjamin Semah's photo
Benjamin Semah
·Oct 2, 2022·

2 min read

Union Types in TypeScript
Play this article

Table of contents

  • Introduction
  • Syntax for Union Types
  • Examples
  • Conclusion

Introduction

What do you do when you want a variable to be able to take more than one type? You use union type. Union types enable you to create a variable that can take a combination of more than one type.

Ideally, you would want to define a unique type for each variable. However, there are times when, for good reason, we will need to allow some room for flexibility. Fortunately, TypeScript makes provision for that. With union types, we can specify multiple types for a single variable.

Syntax for Union Types

Union types are defined by placing the pipe symbol (|) between the names of the types. The syntax is as follows.

let myVariable: type1 | type2

Examples

Let's see some examples below.

let contact: string | number;

contact = "name@mail.com"
contact = 123

In the example above, the contact variable can take either a string or a number. The above example allows the contact variable to take any of the two types defined. It is also possible for the union type to include more than just two types.

Conclusion

The union type can be helpful in situations where you aren't sure of the specific type to expect. However, you know that it can only be one of some specific types. As mentioned earlier, this allows you to maintain strictness of type yet with some degree of flexibility.


Thanks for reading.

Let's connect on LinkedIn | Twitter


 
Share this