Union Type

Union Types means that the value can be one of multiple types.

let someValue: string | number;
someValue = 'nice'
someValue = 88
let someValue: string | number;
someValue = true

// index.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'.
//   Type 'boolean' is not assignable to type 'number'.

The union type uses | to separate each type. The meaning of let someValue: string | number here is that the allowed type of someValue is string or number, but not other types.

Access to the properties or methods of the union type When TypeScript is not sure which type the variable of a union type is, we can only access the properties or methods common to all types of this union type:

function getLength(something: string | number): number {
    return something.length;
}

// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.

In the above example, length is not a common attribute of string and number, so an error will be reported. It is no problem to access the shared attributes of string and number:

function getString(something: string | number): string {
      return something.toString()
}

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

let someValue: string | number;
someValue = 'nice'
console.log(someValue.length) //  5

someValue = 8
console.log(someValue.length) //  5

// index.ts(5,30): error TS2339: Property 'length' does not exist on type 'number'.