Union Types, Type Guards, and Aliases
Learn to combine types and understand type guards and aliases.
We'll cover the following...
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 numberfunction printObject(obj: string | number) {// Log the value of objconsole.log(`obj = ${obj}`);}// Call printObject with a number valueprintObject(1);// Call printObject with a string valueprintObject("string value");
Printing an object of string or number type
-
We define a function named
printObject
on line 2 that has a single parameter namedobj
. -
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 numberfunction addWithUnion(arg1: string | number,arg2: string | number) {// Return the sum of arg1 and arg2return arg1 + arg2;}
Type error
- We define a function named
addWithUnion
on lines 2–5 that accepts two parameters and returns their sum. Thearg1
andarg2
parameters are union types and can therefore hold either astring
or anumber
.
Unfortunately, this ...