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

What is the use of pipe symbol in TypeScript?

1个答案

1

In TypeScript, the pipe symbol (|) is primarily used to define union types. Union types allow you to define variables that can be one of several types, providing greater flexibility and type safety.

Examples

Suppose we have a function that accepts a parameter which can be a string or a number. We can use the pipe symbol to define the type of this parameter:

typescript
function formatInput(input: string | number) { if (typeof input === 'string') { console.log(`Input is string: ${input}`); } else { console.log(`Input is number: ${input}`); } } formatInput('hello'); // Output: Input is string: hello formatInput(123); // Output: Input is number: 123

In this example, the type of input is declared as string | number, meaning input can be of type string or number. Inside the function, we can use typeof to check the actual type of input and handle the data accordingly.

Summary

Using the pipe symbol to define union types is one of the powerful features provided by TypeScript, enabling functions and variables to handle multiple data types more flexibly while maintaining code cleanliness and type safety.

2024年11月29日 09:31 回复

你的答案