HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / TypeScript Union Types

TypeScript Union Types

In TypeScript, you can define a variable which can have multiple types of values (i.e. number, string etc). This is called union type. A union type allows us to define a variable with multiple types. This is achieved by using the pipe ('|') symbol between the types.

Union types helps in some situations when migrating from JavaScript code to TypeScript code.

Union Type Syntax

As said earlier, use pipe symbol between multiple types which variable can support.

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

Union Type Example

Let’s see an example of typescript union types.

 
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.

Drop me your questions in comments section.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – for Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)