...

/

Union Types, Type Guards, and Aliases

Union Types, Type Guards, and Aliases

Learn to combine types and understand type guards and aliases.

Introduction to unions

TypeScript allows us to express a type as a combination of two or more other types. These types are known as union types, and they use the pipe symbol (|) to list all of the types that will make up this new type.

Consider the following code:

// Declare a function called printObject that takes in a parameter called obj with a type of string or number
function printObject(obj: string | number) {
// Log the value of obj
console.log(`obj = ${obj}`);
}
// Call printObject with a number value
printObject(1);
// Call printObject with a string value
printObject("string value");
Printing an object of string or number type
  • We define a function named printObject on line 2 that has a single parameter named obj.

  • On lines 8 and 11, we call the function printObject with a number and then with a string, respectively.

Type guards

When working with union types, the compiler will still apply its strong typing rules to ensure type safety.

As an example of this, consider the following code:

// Declare a function called addWithUnion that takes in two parameters, arg1 and arg2, with types of string or number
function addWithUnion(
arg1: string | number,
arg2: string | number
) {
// Return the sum of arg1 and arg2
return arg1 + arg2;
}
Type error
  • We define a function named addWithUnion on lines 2–5 that accepts two parameters and returns their sum. The arg1 and arg2 parameters are union types and can therefore hold either a string or a number.

Unfortunately, this ...