Union in TypeScript

  • In TypeScript, a union type allows you to specify that a variable or parameter can have multiple possible types. It is denoted using the pipe (`|`) symbol between the types. This means that the value assigned to a union type variable can be of any of the specified types.
Here's an example to illustrate the concept of a union type:


    function displayValue(value: string | number) {
        console.log(`The value is: ${value}`);
    }

    displayValue("Hello");  // Output: The value is: Hello
    displayValue(42);       // Output: The value is: 42
    displayValue(true);     // Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'

  • In the above example, the `displayValue` function accepts a parameter `value` of type `string | number`. This means that the `value` parameter can be either a string or a number.
  • When calling the `displayValue` function with a string argument (`"Hello"`), the function executes successfully and prints the value. Similarly, when called with a numeric argument (`42`), the function prints the numeric value.
  • However, if you try to call the `displayValue` function with a boolean argument (`true`), it will result in a compilation error. This is because the boolean type is not included in the union type `string | number`.
  • Using union types, you can define variables or parameters that can accept values from multiple types, providing flexibility in your code. This is especially useful when working with functions or APIs that can handle different types of inputs or outputs.
  • You can also combine union types with other TypeScript features like type guards and conditional statements to perform type-specific operations or validations based on the actual type of the value within the union.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...