EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Union Types
 

TypeScript Union Types

Updated April 19, 2023

TypeScript Union Types

 

 

Introduction to TypeScript Union Types

In TypeScript union types is one of the feature and it is mainly used for to define the user variable which can have multiple set and data types value like integer or number, character, string, float etc these combined data type are referred as union types and it is allowed for the variable with multiple set of data types this can be achieved and implemented using the operator like | pipe symbol for utilising all the data types with the single operands or the other functional parameters whenever we used the variable the variable code also act as the union type model on the script.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

The TypeScript has many different modules, packages and namespace etc. Like that we used different data types for segregate the datas and utilise the data type values with standard inputs and outputs. If we use different set of input data types and while we convert or casting the type values to other type formats it may also include on the union type in the TypeScript.

var or let variable name: string | number| boolean| bigint| symbol| null
variable name = 123434;
variable name="siva";
variable name=true;
variable name=null;
variable name=undefined;

The above codes are the basic syntax for using the union type on TypeScript. We can declare each data type values with the same variable name.

Union Types in TypeScript

TypeScript union is one of the feature and it is mainly for to allow more than one data types for the single variable or any other function or method parameter as the arguments. The union has a different type for each type the occasionally we will run into the TypeScript library but most probably that the expected parameter to be either number or integer or any other string formats.

1. Discriminating Unions

It is one of the union type and it is a common technique for single variable fields which has used in the literal types. The TypeScript narrow is segregated the datas in the down model for the most possible current data type which is declared on the user end.

Let s take a example like single variable field will be shared with the three different union type states like “success, failed, pending” for each state of the output the input variable is of same type.

Example:

Code:

type pending = {
status: "your input is pending state";
errorcode:number;
};
type success = {
status: "your input is success";
errorcode: number;
};
type failed = {
status: "your input is failed state";
errorcode: number
};
type currentState =
| pending
| success
| failed;
function demo(status: currentState): string {
status.errorcode;
switch (status.status) {
case "first":
return "your inputs are still pending state";
case "second":
return `success ${status.errorcode} your inputs are still pending state`;
case "third":
return `pending ${status.errorcode} pending`;
}
}

Output:

TypeScript Union Types 1

2. Union Exhaustive Check

It is of another union type like the TypeScript compiler want to tell us its possible for not to cover all of the variants are from the discriminated union type. So its combine and followed with the discriminating union i.e) when we want to change from one state(pending) to another state (success or failed) the application backend has follow up the logger technique to update the current status of the application.

Example:

Code:

enum first {
Ok = 'Ok',
Cancel = 'Cancel',
}
function demo(i: first): string {
switch (i) {
case first.Ok:
return 'welcome';
}

Output:

TypeScript Union Types 2

3. Unions With Same Common Fields

Suppose if we have the variable value with same union type that time we can access only the member like parent-child relationship like inheritance concept. So the member of the union type will be common to all of the data types which is related to the same variable field.

Example:

Code:

interface A {
demo(): void;
demo1(): void;
}
interface B {
demo2(): void;
demo(): void;
}
interface C {
demo3(): void;
demo2(): void;
}
declare function example(): A | B | C;
let eg = example();
eg.demo();
eg.demo3();

Output:

TypeScript Union Types 3

Examples of TypeScript Union Types

Given below are the examples of TypeScript Union Types:

Example #1

Code:

function demo(vars) {
if (typeof vars == "boolean") {
console.log(vars);
} else {
var i;
for (i = 0; i < vars.length; i++) {
console.log(vars[i]);
}
}
}
demo("Have a Nice day");
console.log("Your inputs are converted and printed it on the array format");
demo(["Sivaraman", "BTech", "Tiruppur", "IT Professional"]);

Output:

TypeScript Union Types 4

we used single function

In the above example we used single function with single parameter it may be of any type. We can evaluate the type using if statement with boolean as the evaluation type and printed it on the requested and responded output on the console.

Example #2

Code:

function demo1(eg: (string | number)) {
if(typeof(eg) === "number")
console.log('Your input is number format.')
else if(typeof(eg) === "string")
console.log('Your input is string formtted.')
}
demo1(49);
demo1("GFG");
demo1(true);
var first;
var j;
first = [10, 5, 1989, 12345];
console.log("Your inputs are converted to array formats");
for (j = 0; j < first.length; j++) {
console.log(first[j]);
}
first = ["Welcome", "To", "My Domain"];
console.log("Your inputs are string formatted");
for (j = 0; j < first.length; j++) {
console.log(first[j]);
}

Output:

single function with different parameter

In the second example we used single function with different parameter type with single variable. By using if condition we can evaluate the inputs with consult format. For loop also to iterate the input values and printed it on the output console.

Example #3

Code:

interface A<T>{
firsttype:T;
}
function demo<T>(firsttype:T) : A<T>{
return {firsttype:firsttype};
}
var vars1 = demo("Welcome To My Domain");
var vars2 = vars1.firsttype.length;
var vars3 = demo(true);
var output = vars3.firsttype === true;
if(output == true)
{
console.log(output)
}
else
{
console.log("your input conditions are not evaluated and the output is false");
}

Output:

true

In the final example we used interface and single function while passing the type called ‘T’. We evaluate the input conditions using the boolean type if the condition is satisfied it print the “true” as the output console else it will print the “false”.

Conclusion

In TypeScript we used different set of features for to implement the application with user responsiveness and requirements. By using union feature on the TypeScript we can replace and include the other different data types on the script it will help for including the n number of data types with single module on the application then the performance will be more fast and reduces the memory consumption. It is used to add the n number of data type values with single variable reference.

Recommended Articles

We hope that this EDUCBA information on “TypeScript Union Types” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript Array of Objects
  2. TypeScript keyof Enum
  3. TypeScript Set
  4. TypeScript Abstract Class

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - ENROLL NOW