2.4 Union types

TypeScript allow us to explicitly declare the types of the variables in a program using what is known as optional type annotations. In this chapter, we will learn about some of the advanced features of the optional type annotations. We will start with union types.

Getting Ready

All you need to be able to use union types is an installation of TypeScript version 2.0 or higher.

How to do it…

Imagine that you have to use the following class to execute a command:

class Command {
  command: string;
  args: string[];
}

You could use the optional type annotation and a union type declaration to allow one command or multiple commands to be passed to a hypothetical “run” function:

function run(command: Command | Command[]) {
  // ...
}

How it works…

Union types allow us to explicitly declare that the value of a variable can be of multiple types. In the example above we have declared that the type of the command parameter can be an instance of the command class or an array of instances of the command class. This means that we can invoke the run function in two different valid ways:

const command1 = new Command();
const command2 = new Command();
const commands = [ command1, command2 ];

run(command1);
run(commands); 

Source Code

Union types


Shiv Kushwaha

Author/Programmer