Type unions in TypeScript allow us to define a variable, parameter, or return type that can be one of several specified types. This feature provides flexibility while maintaining type safety, ensuring that the variable can be one of the defined types but nothing else.
Union types are particularly useful when a variable or function can operate on multiple types of data. This can be common in scenarios like handling different kinds of user inputs, API responses, or flexible function arguments.
Syntax
The syntax for defining a union type uses the vertical bar (|) to separate the types.
Examples
Basic Example
Function Paramters
A function that accepts a parameter of a union type.
Union Types with Arrays
Type Guards
To perform operations safely on union types, we often need to use type guards. Type guards help narrow down the type within a specific block of code.
Union Types in Interfaces
Complex Example: Handling Different Response Types
Let’s consider a function that can return either a success result or an error result:
Summary
Definition: Union types allow a variable or function parameter to be one of several specified types.
Syntax: Use the vertical bar (|) to separate the types.
Flexibility with Safety: Union types provide flexibility while maintaining type safety by restricting the types to the specified union.
Type Guards: Use type guards to safely perform operations on union types.
Usage Scenarios: Union types are useful for handling multiple input types, flexible function parameters, and varying response types.