TypeScript Union Types

In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc).

A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ('|') symbol between the types.

The union types help in some special situations. For example, when migrating from JavaScript code to TypeScript code.

1. Union Type Syntax

To define a union type, use the pipe symbol between multiple types which a variable should support.

 
let myVar: string | number;	//myVar can store string and number types

2. Union Type Example

Let’s see an example of union type in TypeScript.

 
let myVar : string | number;		//Variable with union type declaration

myVar = 100;			//OK
myVar = 'Lokesh';		//OK

myVar = true;			//Error - boolean not allowed

Here, the myVar variable can hold both number and string, which allows us to have the flexibility to use both data types.

The TypeScript compiler makes sure that it alerts us if we try to assign a type of value that was not defined.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.