Union Type in TypeScript

Last updated on 14 Jan, 2023

As the name suggests, union type helps variables to have more than one type. Here is a variable that can have either a number type or a string type or a boolean type.

let a: number | string | boolean;

| is the union operator. All the assignments below are valid due to union operator.

a = 10;
a = "Apple";
a = true;

But, if we try to assign an object literal to a, it throws error as shown below:

Invalid assignment to union type
--- ○ ---
Joby Joseph
Web Architect