Typescript Union Types

Union Types in Typescript allows a variable to have the ability to store a value of several types. We define union types by using a pipe (|) to separate each of the possible types. Hence, number | string | boolean is the type of a variable, which can have the value that can be a number, a string, or a boolean.


The syntax for declaring the variable of union type is as shown below

let : type1 | type2 | .. | .. | typeN


let a:number|string

In the following example, the variable a can take either number or string. Hence you can only assign either a number or string to it. If you assign any other type like boolean (a=true), the compiler will throw an error.

Union Types As Function Parameter

The following example shows how you can use union Types to restrict the function Parameter. Invoking the function with any other argument other than the string or number will result in a compile error.

Here is an use case for using the Unions. The function takes either string or array of string and prints the content back.

Function Return Types

Use them as function return types as shown below.

Not just Primitives

We can create union types from any type, not just primitive types. The following example shows the getName function can take the argument that is of Product and Employee.

Literal Types

Literal types is one of very useful features of the TypeScript. Its power comes when you use it along with the Union Types.

In the following example, you only pass the string literals "start", “stop", true & false to the engine function. The string "Start" is not allowed. The string variable containing the "start" is also not allowed.

You can also define the function as follows

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top