Table of contents
1.
Introduction
2.
Union Type
2.1.
TypeScript
2.2.
Syntax
2.3.
TypeScript
2.4.
When to Use it?
2.5.
Example
2.6.
TypeScript
3.
Generic Type 
3.1.
TypeScript
3.2.
Syntax
3.3.
TypeScript
3.4.
Example
3.5.
TypeScript
4.
Difference Between Generic Type and Union Type
5.
Frequently Asked Questions
5.1.
Can we use union types and generic types together in TypeScript?
5.2.
What is the difference between union types and generic types in Typescript?
5.3.
When should we use generic types vs union types in TypeScript?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Generic Types vs Union Types

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

Introduction

Typescript is a typed superset of Javascript that adds static type checking to the language, which means TypeScript can help us catch errors at compile time instead of runtime. In TypeScript, we can define variables that can have multiple types of values. Therefore, TypreScript can merge two different types of data, such as numbers or strings, into a single type which is then known as union type. 

Generic Type vs Union Type

Generics is an essential feature in TypreScript that allows developers to create reusable code components which work with different types rather than a single type. In this article, we will see Generic Types vs Union Types in detail.

Union Type

Union types are useful when a value can be more than a single type, for example, when a property is a string or number. A union type is a powerful and effective tool that accepts arguments of different types. For example:

  • TypeScript

TypeScript

Declare function trial(x: string | boolean)

The argument type can be a boolean or string.

Syntax

  • TypeScript

TypeScript

let UnionT: string | number; 

Here, UnionT will store string and number types. Also, a pipe symbol is used between multiple types that a variable should support.

When to Use it?

Following are times when Union types are used:

  • The return type doesn't change based on the type of the argument
     
  • When we know all the possible members of every union type at the moment of the declaration of the function

Also, whenever we use Union types for typing functions, there is no need to type the return type explicitly.

Example

An example of Union Type is as follows:

  • TypeScript

TypeScript

let empId: (string | boolean);
empId = 101;  // Compilation Error
empId = "CMT";  // No Error
empId = false;  // No Error

let studentId: string | boolean;
studentId = 244; // Compilation Error
studentId = "CAR"; // No Error
studentId = true;  // No Error

Output:

output

In the above example, we can see that empId is of union type that is denoted with (string | boolean), So the arguments we can assign are string and boolean only. Therefore, it is giving a compilation error when we are assigning the variable with a type other than string and boolean. 

Generic Type 

Generic types allow us to create reusable components. This makes sure that the program is scalable and flexible for the long term. They offer a way to make the components work with any data type and are not limited to a single data type. Hence, components are utilized or called with a wide range of data types. 

Generics have the syntax <T> where T represents a passed-in type. Generic type parameters or type parameters are the other names for the generic types declared inside angle brackets. We can define multiple generic types in a single type. for example, <T, K, A>.

For example:

  • TypeScript

TypeScript

function trial<T>(value: T): T

{

   return value;

}

const res = trial<number>(150);

The result variable of the above code snipped is of type number. We are explicitly telling TypeScript that we want the generic type parameter T of the identity function to be of the type number by handing in the type with the <number> code. This may enforce the number type as the argument and return value.

Syntax

  • TypeScript

TypeScript

function student<T>(arg: T): T
{
   return arg;
}

let num1 = student<number>(150);
let num2 = student<string>("Lucky");

 

Example

  • TypeScript

TypeScript

function getArray(items: any[]): any[]
{
   return new Array().concat(items);
}
let MynumArr = getArray([400, 500, 600]);

let MystrArr = getArray(["David", "Hema"]);
MynumArr.push(700);
MystrArr.push("Hello");
MynumArr.push("Bye");
MystrArr.push(700);

console.log(MynumArr);
console.log(MystrArr);

Output:

output

The type variable <T> is declared in the code sample above, along with the method getArray <T>. The type of arguments and return value are specified using the type variable T. It means that the data type of the arguments and return value will be the same as the data type that is given at the time of the function call.

The MynumArr and MystrArr were passed to the generic function getArray() when it was called. For instance, running the function getArrnumber>([400, 500, 600]) will change T to the number, resulting in numArr as the type of the parameters and the return value. The type of parameters and return value when using the function getArray<string>(["David", "Hema"]) will also be MystrArr. Now, the compiler will throw an error if we try to add a string in the MynumArr or a number in the MystrArr array.

Difference Between Generic Type and Union Type

Features

Generic Type

Union Type

Definition  Generic type in Typescript is a feature that provides developers to create reusable code components. A union in Typescript is a feature that is used to show a value that can be one of multiple types.
Description It is a type that can be used with multiple types. It is defined using a parameter, which is a placeholder for a particular type. It is a type that can be one of various types. It is defined using a vertical bar.
Syntax <T> ‘number’
Advantage A generic type can enhance type safety and code readability. It can be used to depict more complex data structures.
Disadvantage It can be more difficult to use or understand. It can result in type errors of the value is not one of the allowed types.

Frequently Asked Questions

Can we use union types and generic types together in TypeScript?

Yes, we can use union types and generic types together in Typescript. For example, we can create a generic type that can depict any type of array that contains only strings or numbers.

What is the difference between union types and generic types in Typescript?

The main difference between union types and generic types is that generic types can represent a wider range of values. A generic type can be used to present any data type of data, while a union type can only show a value from a particular set of types.

When should we use generic types vs union types in TypeScript?

We should use union types when we want to show a value that can be one of the various different types. And we should use generic types when we want to create reusable code that can work with different types of data.

Conclusion

In this article, we have discussed Generic Types vs Union Types. We have seen the definition, syntax, use case, and example in detail. We hope this blog has helped you enhance your knowledge of Generic Types vs Union Types. If you want to learn more, then check out our articles:

 

Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must have a look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass