乐闻世界logo
搜索文章和话题

What is the " Union " type and how is it used in TypeScript?

1个答案

1

In TypeScript, the "Union" type is an advanced type that allows a value to be of multiple distinct types. Simply put, Union types connect multiple types using the pipe symbol (|), enabling variables to store values of different types. This type's primary purpose is to enhance code flexibility and maintainability, allowing a variable to be safely specified as one of several possible types.

Union Type Definition

The definition of Union types is straightforward. For example, if you have a variable that can be either a number or a string type, you can define it as:

typescript
let myVar: number | string;

This definition indicates that myVar can store either a number or a string.

Usage Example

Suppose we are writing a function that accepts a parameter which can be either a number or a string. When the parameter is a number, it directly prints the number; when it is a string, it prints the length of the string. We can implement it as follows:

typescript
function printNumberOrStringLength(input: number | string) { if (typeof input === "number") { console.log("Number is:", input); } else { console.log("String length is:", input.length); } } printNumberOrStringLength(123); // Output: Number is: 123 printNumberOrStringLength("hello"); // Output: String length is: 5

In this example, we first define a parameter input of type number | string, meaning input can be either a number or a string. Inside the function, we use the typeof operator to check the type of input and execute different logic based on the type.

Summary

The Union type is a highly practical feature provided by TypeScript, allowing variables to have greater flexibility while maintaining type safety. This is particularly useful for scenarios that require handling multiple data types, such as processing external data or user input. By appropriately utilizing Union types, you can effectively enhance the robustness of applications and improve development efficiency.

2024年8月2日 13:51 回复

你的答案