Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
communitycreator

What is a TypeScript union?

Gutha Vamsi Krishna

Overview

In TypeScript, we need to specify data types for variables.


let a:string;

We might come across a situation where the data can be of different data types, depending upon the situation.

For example, if we want to store string and boolean in variable a, then we use TypeScript union.

  • You can combine different data types.

  • Use the pipe | operator to separate data types.

Syntax


let variableName:datatype 1| datatype 2 | ... | datatype n

Code

Example 1

In the code snippet below:

  • We create variable a with types string and boolean.

  • In line 2, we assign the value John, which is of string type, to a.

  • In line 3, we assign true, which is of boolean type, to a.

let a:string | boolean;

a = "John"
console.log(a)

a = true
console.log(a)

Example 2

The compiler will throw an error if we assign values of types other than the specified data types.

In the following code snippet, we assign value 1, which is of number type, to a.

  • The compiler will throw the error Type '1' is not assignable to type 'string | boolean'.
let a:string | boolean;
a = "John"
a = true

//will throw error
a = 1

Example 3

We can create custom types using TypeScript unions and type keywords so that we can assign new custom types to different variables.

In the code snippet below:

  • We create a customType that represents data types string, number, and boolean.

  • In lines 3 and 4, we create variables a and b with the type customType.

// creating custom type usign union
type customType =  (string | number | boolean);

//assigning custom type
let a:customType;
let b:customType;

a = 5
console.log(a)

a = "John"
console.log(a)

a = true
console.log(a)

b = 10
console.log(b)

RELATED TAGS

typescript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring