Generic Types vs Union Types

Learn via video courses
Topics Covered

Overview

In TypeScript, variables can be defined that can have multiple types of values. So, TypeScript can merge two different types of data (like a number, string, etc.) into a single type which is further known as union type. They are capable to express a variable defined with multiple types. Generics is an important feature in TypeScript that enables developers to create reusable code components which work with different types instead of a single type. Generics are used in almost all programming languages that have support for Object Oriented Programming.

Union Type Signature

TypeScript union types are useful when it comes to typing anything that can have multiple type definitions. Union Types are a powerful tool to express a variable with multiple types.

Union types is an effective tool that accepts arguments of different types. For example:

The argument type can either be a string or boolean.

Union Type Syntax

To define a union type, we use a pipe symbol | between multiple types that a variable should support.

When to Use Union Type

Union types are used:

  • When we are aware of all the possible members of each union type at the moment of the declaration of the function.
  • The return type doesn't change depending on the type of argument.

Also when we use union types for typing functions, we are not required to type the return type explicitly.

Example by Implementing Union Type

Following is the example of implementing union type:

In the above example, variable empCode is of union type that is denoted with (string | number). So, we can only assign a string or a number to it. Therefore, there occurs a compilation error when we assign the variables with a type other than string and number.

Generic Type Signature

Generic types offer us to create reusable components. This ensures that the program is flexible and scalable for the long term. They provide a way to make the components work with any kind of data type and they are not restricted to a single data type. Hence, components are called or used with a variety of data types.

Generics, appear in code inside the angle brackets, in the format <T> where T represents a passed-in type. <T> can be read as generic type of T. The generic types declared inside the angle brackets are also called generic type parameters or type parameters. Multiple generic types can appear in a single type definition like <T, K, A>.

Example

Explanation

In the above code snippet, the result variable has the type number. By passing in the type with the <number> code, we are explicitly letting TypeScript know that we want the generic type parameter T of the identity function to be of the type number. This may enforce the number type as the argument and return value.

Generic Type Syntax

In generics, we are required to write a type parameter between the open (<) and close(>) brackets that make the type strongly typed collection. Generics uses a special kind of variable <T> that denotes types. The generics collection contains similar types of objects.

Syntax

When to Use Generic Type

Following is the example of to understand the usage of the generic type in TypeScript:

Output

In the above code snippet, the getArr() function accepts an array of type any. The function is used to create a new array of type any, concatenating items to it and returning a new array. As we have used type any for the arguments, we can pass any type of array to the function. We can add numbers to the numArray and strings to the strArray but not numbers to the strArray or vice-versa.

To solve the above problem, TypeScript introduced the concept of Generics. Generics uses a type variable <T> that denotes types. The type variable recalls the type that the user provides and works with that particular type only. This process is known as preserving the type of information.

Example by Implementing Generic Type

Following is the example to understand the implementation of the generic type in TypeScript:

Explanation

In the above code snippet, the type variable <T> is declared with the function in the angle brackets getArr<T>. The type variable T is used to specify the type of arguments and return value. This means that the data type that will be specified at the time of the function call, will also be the data type of the arguments and return value.

We have called a generic function getArr() and passed the numArray and strArray. For example, calling the function getArr<number>([400, 500, 600]) will replace T with the number and so, the type of arguments and return value will be numArr. Likewise, calling the function getArray<string>(["Brian", "Lara"]), the type of arguments and return value will be strArr. Now, the compiler will throw an error if we try to add a string in the numArray or a number in the strArray array.

We can also a generic function without specifying the type variable. The compiler uses type inference to set the value of T on the function based on the data type of argument values.

Difference Between Generic Type and Union Type

Here are some key differences between Generic Types and Union Types:

Generic TypesUnion Types
Generics is an important feature in TypeScript that enables developers to create reusable code components.A union is an important feature that is used to express a value that can be one of several types.
Generics works with different types instead of a single type.TypeScript can merge two different types of data (like a number, string, etc.) into a single type which is further known as union type.
In Generics, we are required to write a type parameter between the open < and close > brackets. Further, we use a type variable <T> which the user can define while invoking the type.In Unions, Two or more data types can be combined with the help of a pipe symbol between the types.

Conclusion

  • In TypeScript, we use a different set of features to implement the application with user responsiveness and requirements.
  • Union types come into the picture when a value can be more than a single type, such as when a property is a string or a number.
  • Generics can be applied to the function's argument, function's return type, and, class, fields or methods.
  • Advantages of generics include:
    • Type-safety
    • Typecasting is not required
    • Compile-time checking
  • Using generics in our code can save us from repeating the same code over and over again, and make the types we have written more flexible.