TypeScript

10. Understanding Union Types in TypeScript

Understanding Union Types in TypeScript

TypeScript is a statically typed language, which means that variables are expected to hold values of a specific type. However, there are situations where you might want to store multiple types of values in the same variable. For instance, you might need a variable to hold either a string or a number, or you might want to pass a function parameter that can accept either of multiple types.

This is where Union Types in TypeScript come into play. A Union Type allows you to define a variable or function parameter that can hold values of more than one type. You can combine types using the pipe symbol (|) to specify the possible types.

In this blog post, we will explore Union Types in TypeScript, including how to define them, and practical examples showing how to use Union Types in real-world scenarios.


What is a Union Type?

A Union Type in TypeScript allows you to define a variable or a function parameter that can hold values of multiple types. This gives you the flexibility to handle different types of data in a single variable.

To create a union type, you use the pipe (|) symbol between the types. For example, you can define a variable that can hold either a string or a number.

Syntax:

let variable_name: type1 | type2;

Here, variable_name can accept either type1 or type2.

Example 1: Union Type for Variable

In this example, we define a variable that can hold either a string or a number.

let student_details: string | number;
student_details = 50; // A number value
console.log("Roll Number of the student is: " + student_details);

student_details = "Science"; // A string value
console.log("He is studying: " + student_details);

Output:

Roll Number of the student is: 50
He is studying: Science

In this example:

  • The variable student_details is defined with a Union Type (string | number), which means it can hold either a string or a number.

  • We first assign a number (roll number), and later assign a string (course name). Both assignments work fine.


Union Types in Functions

Union types can also be used in function parameters. This allows you to create functions that can accept multiple types of arguments, providing flexibility when dealing with different data formats.

Example 2: Union Type in Function Parameters

Let’s create a function that can accept either a single name (string) or an array of names (array of strings). The function will behave differently depending on the input type.

function processNames(names: string | string[]) {
if (typeof names === "string") {
console.log(`Single Name: ${names}`);
} else {
console.log("Multiple Names:");
names.forEach((name) => {
console.log(name);
});
}
}

// Single name as string
processNames("John Doe");
// Output: Single Name: John Doe

// Multiple names as an array
processNames(["Alice", "Bob", "Charlie"]);
// Output:
// Multiple Names:
// Alice
// Bob
// Charlie

Explanation:

  • The function processNames takes a parameter names, which can either be a single string or an array of strings.

  • If names is a string, it prints the single name.

  • If names is an array, it loops through and prints each name.


Union Types with Arrays

You can also use union types with arrays. This allows you to create arrays that hold values of different types. For example, you might want to store a mix of numbers and strings in the same array.

Example 3: Union Types with Arrays

let items: (number | string)[] = []; // Union type array (number or string)

items.push(10); // Add a number
items.push("Laptop"); // Add a string

console.log("Items in the array:");
items.forEach(item => {
console.log(item);
});

Output:

Items in the array:
10
Laptop

In this example:

  • The array items is defined as a union type array that can hold either numbers or strings.

  • We add a number (10) and a string (“Laptop”) to the array and then print both items.


Union Types in Objects and Interfaces

Union types are also useful when defining properties in objects and interfaces. For instance, in a user profile system, you might want to define a status property that could either be a string (for a status message) or a boolean (indicating whether the user is online).

Example 4: Union Types with Objects and Interfaces

interface UserProfile {
name: string;
status: string | boolean; // Status can be a string or a boolean
}

let user1: UserProfile = {
name: "John",
status: "Active", // Status is a string
};

let user2: UserProfile = {
name: "Alice",
status: true, // Status is a boolean
};

console.log(`${user1.name} - Status: ${user1.status}`); // Output: John - Status: Active
console.log(`${user2.name} - Status: ${user2.status}`); // Output: Alice - Status: true

Explanation:

  • The status property in the UserProfile interface can hold either a string or a boolean.

  • user1 has a string status, while user2 has a boolean status.


Union Types for Mixed Data Handling

In real-world applications, you might encounter situations where you need to handle mixed types of data in a flexible way. For example, a shopping cart might contain items of different types (e.g., product IDs and product names).

Example 5: Union Types for Shopping Cart

let cart: (number | string)[] = []; // Union type array (number or string)

// Adding product IDs and product names
cart.push(1001); // Product ID (number)
cart.push("Laptop"); // Product name (string)

console.log("Cart contents:");
cart.forEach(item => {
console.log(item);
});

Output:

Cart contents:
1001
Laptop

In this example:

  • The shopping cart cart is defined as a union type array that can hold both numbers (product IDs) and strings (product names).

  • We add both a product ID and a product name, demonstrating the flexibility of union types.


Conclusion

Union types in TypeScript provide a powerful way to handle variables, function parameters, and arrays that can accept multiple types. This flexibility is especially useful when you need to work with mixed types of data, making your code more dynamic and reusable.

In this blog post, we covered:

  • Union Types in Variables: How to define variables that can hold multiple types of values.

  • Union Types in Functions: How to create functions that accept parameters of multiple types.

  • Union Types with Arrays: How to define arrays that can hold values of multiple types.

  • Union Types in Objects and Interfaces: How to define object properties that can accept multiple types.

  • Real-World Examples: Practical scenarios where union types can be applied.

By using union types, you can write more flexible, adaptable, and cleaner TypeScript code while still leveraging TypeScript’s static typing system.

Leave a Reply

Your email address will not be published. Required fields are marked *