Union Types, Type Guards, and Aliases
Learn to combine types and understand type guards and aliases.
We'll cover the following...
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:
Printing an object of string or number type
-
We define a function named
printObjecton line 2 that has a single parameter namedobj. -
On lines 8 and 11, we call the function
printObjectwith 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:
Type error
- We define a function named
addWithUnionon lines 2–5 that accepts two parameters and returns their sum. Thearg1andarg2parameters are union types and can therefore hold either astringor anumber.