1. Union type

Union Types indicate that the value can be one of multiple Types.

Joint type using | separated for each type.

In the code above we can see that the variable unionType is defined. We specify either a string type or a number type, assign values to each, and print out the string “six” and the number 6. This is the unionType;

We get an error when we assign unionType to Boolean type yes;

2. Access the properties or methods of the union type

When a variable of a union type is uncertain of its type, we can only access properties or methods that are common to all types of the union type.

In the getReturn method above, the argument something is a string or a number associative argument. :number means that the return value is number, but we find that when we execute this function, we get an error. Length is a string attribute, but not a number attribute. We should return a common attribute for both types. We can change this to look like this:

We can convert numeric to string and return a string value.

When a variable of the union type is assigned, a type is inferred according to the rules of type inference:

let myNumber: string | number; myNumber = 'seven'; console.log(myNumber.length); // 5 myNumber = 7; console.log(myNumber.length); Index. Ts (5,30): error TS2339: Property 'length' does not exist on type 'number'.Copy the code