Union Types, Type Guards, and Aliases
Explore how to define union types in TypeScript to combine multiple types and use type guards for safe type checking within your code. Understand how to implement type aliases to simplify and reuse complex type unions effectively.
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:
-
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:
- 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.