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:
typescriptfunction 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.