Table of contents
1.
Introduction
2.
Union in Typescript
2.1.
Syntax of union
3.
Passing Union Type in Function Parameter
4.
Arrays as Union Types
5.
Union can replace Typescript Enums
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Union in Typescript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Typescript is a strongly typed programming language. It is the syntactic superset of javascript that adds more advanced features to the language. It is designed for the development of large projects. Union is one of the features supported by typescript. It is a particular operation that is used to combine different parameters.

In this blog, we will learn about the union in typescript that allows us to store a value of one or more types in a variable.

Union in Typescript

Union in typescript allows us to combine different data types for a variable. It can be string, numeric, double, etc. A union type is a powerful way to express a variable of various kinds. Union types are represented using a pipe(‘|’) symbol.

Syntax of union

(string | number | double | float)

 

Example 1:

let num : number | string;  
num = 3000;  
console.log("Numeric value of the num: " + num);  
num = "Welcome to CodingNinjas!";  
console.log("String value of the num: " + num);

 

Output 1:

In the above example, as we have defined ‘num’ as the union of string and numeric, that’s why it can only take a string or numeric values. Any other data type will generate a compilation error. Consider the below example:

 

Example 2:

let num : number | string;  
num = false;  
console.log("Numeric value of the num: " + num);  
num = "Welcome to CodingNinjas!";  
console.log("String value of the num: " + num);

 

Output 2:

Here, ‘num’ as a boolean variable is not supported in the second line and generates a compilation error since we have declared ‘num’ as the union of number and string.

Passing Union Type in Function Parameter

We can pass the union type as a parameter. Let’s try to understand this through some examples:

Example 1:

Function display(a: number | string)  
{  
    if(typeof(a) === "number")  
        console.log('The value ’+ a + ‘ is of type number.');  
    else if(typeof(a) === "string")  
        console.log('The value ’+ a + ‘ is of type string.');  
}  
display(3000);  
display("Welcome to Coding Ninjas!");

 

Output 1:

In the above example, variable ‘a’ is of union type, taking number and string values.

 

Example 2:

function addition(a: number | string, b: number | string) {
    if (typeof(a) === 'number' && typeof(b) === 'number') {
        console.log(a + b);
    }
    else if (typeof(a) === 'string' && typeof(b) === 'string') {
        console.log(a.concat(b));
    }
   else
        console.log('Parameters must be numbers or strings');
}
addition(24,36);  
addition("Welcome to","Coding Ninjas"); 
addition(“Welcome”,24);

 

Output 2:

In the above example, we have two variables, ‘a’ and ‘b’ of union types. They can take values of a string and numeric data type. If both the variables are of numeric type, we will simply add them, and if they are of string type, we will have to concatenate the given strings.

Arrays as Union Types

We can also pass an array in union type. The array can represent any of the available data types.

Example:

let arr: number[] | string[];
//Declare numeric array
arr = [1, 2, 3, 4, 5, 6, 7];
  
console.log("Print the array elements");
  
// Loop to display array elements
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
  
// Declare string array
arr = ["Consider", "this", "an", "Example: ", "CodingNinja"];
  
console.log("Print the array elements");
  
// Loop to display the array elements
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

 

Output:

Union can replace Typescript Enums

Typescript enums allow developers to declare a set of named constants. By default, enums begin their numbering from 0, but we can also change this setting manually to one of its elements.

Example:

Export type continents= ‘Asia’ | ‘Africa’ | ‘NorthAmerica’ | ‘SouthAmerica’ | ‘Europe’ | ‘Antarctica’ | ‘Australia’
const mycontinent: continents= 'Asia';
console.log(mycontinent);

 

Output:

Frequently Asked Questions

Q1. What do three dots mean in typescript?

Ans: Three dots refer to the spread operator. The spread operator returns all the values of an array. 

Examples:

Method 1: 

let arr= [1,2,3];
return [1,2,3];

 

Method 2:

let arr= [1,2,3];
return [...arr];

Both methods 1 and 2 will produce the same outputs.

 

Q2. What is an intersection in typescript?

Ans:  An intersection type creates a new type by combining all the existing types. This new type has all the features of the existing type. It is represented by the ‘&’ symbol.

type typeC= typeA & typeB

 

Example:

interface Identity{
                     name: string;
                     id: number;
                  }
interface Contact{
                    email: string;
                    phone: string;
                 }
type Employee = Identity & Contact.

 

Q3. What is @types in Typescript?

Ans: The type represents the different values supported by typescript. It checks the validity of the existing values before they are stored or manipulated by the program. TypeScript provides data types as a part of its optional type system. The data types are further classified as follows −

  1. Built-in types
  2. User-defined types

Key Takeaways

A typescript union allows us to store a value of one or multiple data type variables. The variable can only be assigned the data types declared within the union. Otherwise, it will generate a compilation error. Union type can also be passed as function parameters and arrays.

Check out this problem - Multiply Strings

If you are a beginner interested in learning and exploring other fields, you can follow our guided path to understand the core subjects of computers and get a good grip on DSA concepts. 

Live masterclass