Union Types and Enumerations Explained

Union Types and Enumerations Explained

TypeScript as a strictly typed language offers many great features such as union types and enumerations.

Features as such are widely used in TypeScript programming and allow developers to write flexible and clean code that is strictly typed.

If you never heard of or used union types and enumerations you should try to incorporate them into your code.

In this article, you will learn more about these features and will be ready to incorporate them into your projects.

Union Types

Union Type is a simple but very flexible feature.

It allows to unify and hold two or more different types under one type.

To use this feature you can declare a variable or use a type alias, and then each type should be separated by a vertical bar |.

See the example below:

Using union types we can even assign values straight away, restricting further not only by type but by value as well:

Enumerations (enums)

Enumerations allow us to define a set of easy-to-read names that we can use in a variable later on.

To define an enumeration we need to use an enum keyword followed by a name, then inside a curly braces, we define a set of meaningful names.

Let’s explore an example of how enumeration looks like:

The example above only has a set of names defined, but doesn’t have any specific values defined.

So in this case values are defined automatically.

The first value is 0, the second is 1, and so on.

If you don’t want to use default values, you can specify a value for each name like this:

Instead of using numbers as values, we can use strings: