TypeScript Union

  • In TypeScript, a Union provide ability to specify that a value can be one of several types.
  • You can define a Union type by using the vertical bar | symbol.

example code:

In this example, data is defined as a Union type that can be either a string or a number.

You can assign values of either type to value, and the type of value will adjust accordingly.

Note: Once you assign a value of a certain type to a Union , you can only use the methods and properties that are common to both types. For example, you can use the toString() method on a number, but not on a string, so the following code would result in a compile-time error:


number does not have concat method. its a string method. hence giving compile time error.

Leave a Comment

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

Scroll to Top