Unions in TypeScript

Learn via video courses
Topics Covered

Overview

Typescript is a strongly typed programming language. It is javascript's acceptable superset, which provides more powerful functions to the language. It is intended for the creation of huge projects. One of the features that typescript provides is union. It is a special process that is used to combine different parameters.

Introduction

A type is a useful way to refer to the many attributes and functions that a value possesses in TypeScript.

A value is anything that can be assigned to a variable, such as a number, text, array, object, or function. Different sorts of values are supported by the TypeScript language. It offers data types for JavaScript, allowing it to be transformed into a strongly typed programming language. Although JavaScript does not allow data types, we may use the data types functionality in JavaScript with the aid of TypeScript.

When an object-oriented programmer wishes to use the type feature in any scripting or object-oriented programming language, TypeScript comes in handy. Before the application uses the specified values, the Type System validates them. It guarantees that the code works as it should.

As an optional Type System, TypeScript supports data types. The TypeScript data type is classified as follows.

typescript data type

Static Types

Static types in the association of type systems mean "at compile time" or "without running a program." Variables, parameters, and objects in a statically typed language have types that the compiler understands at compile time. This information was utilized by the compiler to perform type-checking.

Static types are further subdivided into two groups:

  1. Built-in or the Primitive Type
  2. User-Derived type

TypeScript has five built-in data types, which are listed below.

type script built in data types

1) Number

TypeScript, like JavaScript, stores all integers as floating-point values. These numeric values are processed as though they were data types.

Syntax:

Example:

Output:

2) String

In TypeScript, we will represent the text with the string data type. Strings are used to store textual data. String literals are included in our scripts by surrounding them in single or double quotation marks.

Syntax:

Example:

Output:

3) Boolean

The text and numeric data types can have an infinite amount of values. However, the Boolean data type can only have two. They are "true" and "false" respectively. A Boolean value is a truth value that indicates whether or not a condition is true.

Syntax:

Example:

4) Null

Null denotes a variable whose value is unknown. It, like the emptiness, isn't really helpful on its own. The Null only accepts one value, which is null. The Null keyword in TypeScript is used to specify the Null type, although it is useless because it can only be assigned a null value.

Example:

5) Void

A void is a function return type that does not return any sort of value. It's used when no other data type is available. A variable of type void is useless since it can only be assigned undefined or null. Undefined data types indicate uninitialized variables, whereas null represents variables whose values are unknown.

Syntax:

Example:

User-Defined DataTypes

type script used defined data types

1) Array

An array is defined as a grouping of items of a similar data type. TypeScript, like JavaScript, allows us to work with arrays of values. There are two ways to write an array:

To signify an array of that element type, use the element type followed by []:

2) Tuple

The Tuple data type consists of two sets of values of distinct data types. It enables us to describe an array in which the type of a fixed number of members is known but not the same. For example, if we wish to express a value as a number and a string, we may write it as:

3) Interface

An interface is a structure in our program that serves as a contract. It sets the syntax for classes to use, which implies that a class that implements an interface must implement all of its members. It cannot be created, but it may be accessed through the class that implements it. For type-checking, the TypeScript compiler employs an interface, sometimes known as "duck typing" or "structural subtyping".

Example:

4) Class

Classes are used to generate reusable components and also serve as a template for creating objects. It is a logical entity that stores variables and functions in order to carry out actions. ES6 adds class support to TypeScript. It differs from an interface in that it has an implementation, whereas an interface does not have any implementation.

Example:

5) Enums

Enums are a collection of named constants. Enums in TypeScript can be string-based or numeric-based. Enums start numbering their elements from zero by default, but we may modify this by explicitly assigning the value to one of its members. ES6 adds enum support to TypeScript.

Example:

6) Functions

A function is a logical unit of code that is used to arrange the program. TypeScript, like JavaScript, may be used to build functions as either a named function or an anonymous function. Functions make our code legible, manageable, and reusable. A function declaration contains the name, return type, and parameters of a function.

Example:

Generic

Generic is used to design a component that can operate with several data types rather than just one. It enables the creation of reusable components. It guarantees that the software is both adaptable and scalable in the long run. TypeScript employs generics, with the type variable <T> denoting types. Generic functions also have the same type as that of non-generic functions, with the type arguments provided first, as in function declarations.

Example:

Decorators

A decorator is a sort of data that may be added to a class declaration, method, property, accessor, or argument. It allows you to add annotations as well as a meta-programming syntax to classes and methods. It is used in conjunction with the "@" sign.

A decorator is a beta feature that may be changed in future editions. To enable decorator functionality, either on the command line or in tsconfig.json, we must activate the experimentalDecorators compiler option.

Example:

Output:

TypeScript Unions

We can define a variable in TypeScript that can contain several sorts of values. In other words, TypeScript may combine one or two separate types of data (such as numbers, strings, and so on) into a single type known as a union type. Union types are an effective means of expressing a variable that has numerous kinds. Using the pipe ('|') symbol between two or more data types, they can be merged.

Syntax

Example:

Output:

Function Parameter Passing Union Type

A union in typescript can be sent as a parameter to a function. The following example will help us comprehend it.

Example:

Output:

Example:

The method display() can take either a string or a string array as input. It will create the following JavaScript code after compilation.

Output:

Array Union Type Passing

A union in typescript can be passed to an array in TypeScript. The following example will help us comprehend it. Union in typescript can be used to represent arrays, properties, and interfaces. The following example shows how to utilize the union type with an array.

Example:

Output:

Example:

Output:

Enums Can Be Replaced by Unions

Enums are used to define types that include a set of constants. Enums have index values by default (0, 1, 2, 3, etc.). The enums may be seen in the following example, which provides a list of colors.

Example:

Instead of enums, we may utilize union types to achieve equivalent results in much less time.

Example:

Output:

Benefits of Unions in Typescript

Union in typescript handles a wide range of use scenarios, allowing users to write TypeScript in a way comparable to canonical JavaScript.

It might be difficult to determine the cause of run-time problems in dynamically typed languages such as javascript. Using a type-system, you may verify the type of your parameters and ensure their structure is what you want it to be on a regular basis (for example, when calling a function).

This method frequently results in easier-to-understand errors for your issues, which saves time while debugging and may even identify bugs that you would not have spotted otherwise.

Consider a function that performs some numerical computation, and you inadvertently provide nothing to it. Instead of being perplexed by unexpected mistakes in your function, you quickly realize the issue happened before.

When two types are physically (and preferably functionally) similar, one advantage is that the intersection of traits that they share may be used as a point of abstraction.

When you have two types that are not fundamentally comparable but have similarities in how their information might be processed, using a function to normalize that information into a common abstracted form can be valuable.

TypeScript | Union Types and Enums

Enum is a built-in feature in several computer languages. Javascript, on the other hand, does not support it. Typescript offers Enum that does not exist in javascript by transpiling Enum to IIFE (Immediately-Invoked Function Expression). If a person begins their programming experience using C#, which is commonly used to implement Enums. As a result, when you first started using TypeScript, it was simple to build Enums. People discovered some code implementing something along the lines of the following when working with a fresh team and a new TypeScript project:

After doing some investigation, since you have never seen this annotation before, in TypeScript, we immediately discovered the word for this practice: String Literals Unions.

People were curious as to why the project lacked Enums. As a result, a number of tests are carried out to establish the differences between string literal unions and enums. But first, let's see what exactly this Enum is.

What is Enum?

Enums are one of the many TypeScript features that are not a type-level extension of JavaScript. Enums enable a programmer to define a set of named constants. Enums can help you document purpose or build a set of separate scenarios. Enums in TypeScript can be numeric or string-based. Enum may be used to group and preserve related data. Enum values can be textual, numeric, or a combination of the two.

Code Size Difference

Once TypeScript code is converted into JavaScript code, the code size will change. The use of string literal unions will "reduce" or have no effect on the size of your code. Using enums, on the other hand, will increase the code size. We can, however, do a brief test if you want to see this in action.

  • After Compiling to JavaScript, Test the Code Size

Make a new file called index.ts in a new folder. Also, use npm init to create a package.json file and npm I -D typescript to install typescript.

Then, using the previous TypeScript example, populate the index.ts file.

Finally, use typescript to compile it into JavaScript:

You will see that an index.js file has been produced. When you open it, you'll see it's empty. As a result, the index.js file is 0KB in size. If we change the logic in our index.ts file to create an Enum, it should look like this:

Compile the index.ts file into JavaScript once it has been modified. The outcomes are as follows:

The index.js file size will be equivalent to 1KB in size.

  • Running Conditional Checks and Comparing Values

It was usual practice to utilize enums to do conditional tests with the if or switch expressions. In this manner, you could easily select from a list of possibilities to ensure that variables or property values matched any of the enum values. Fortunately, this is no longer necessary because IDEs are now strong enough to propose values when utilizing literal string unions.

  • Order-Based Enum Values

It is worth noting that the values of enums will be numeric dependent on the order supplied. For instance, the following enum values.

Nike, Adidas, Puma, Reebok, and Jordan are examples of shoe brands. Nike, Adidas, Puma, Reebok, and Jordan will have values of 1, 2, 3, 4, and 5, respectively.

The issue is that if Nike is moved to the bottom, its worth will no longer be 1. When doing conditional checks against numbers, this might result in unanticipated logical problems.

  • Making Use of Enum Strings

Enum strings are a suitable alternative. This will prevent each Enum from being automatically assigned a number value.

It is very important to note that once an enum is converted to an enum string, it cannot be mixed. Attempting to utilize ordinary enums and enum strings, for example, will not work:

If you try to compile this into JavaScript, you will encounter the following error:

TS1061: An enum member must have an initializer.

  • Not Union Strings, but Union Types

To construct a type that may include many strings, we frequently use literal string unions. You may, however, create unions using values other than strings:

This provides further flexibility in the type definition. However, that greater flexibility may result in unexpected behavior in the code if the type of a variable, which might be a text, an integer, or an array of objects, etc., is not clearly understood.

When Should You Use Union in Typescript and Enums?

  • If you want to optimize your code and minimize the bundle size while compiling into JavaScript, unions in typescript are suggested since they do not produce unnecessary code or JavaScript objects.
  • If you need to iterate over a set of values, enums are the way to go, even if it means compromising code size optimization.

The drawbacks of using Enum

  • Due to reverse mapping (String enum does not contain reverse mapping), the Javascript transpiler produces an object at run-time when evaluating Enum.
  • When you use Enum, it generates an additional code (reverse mapping) that includes IIFE.
  • Enums in Typescript is highly useful because there is nothing like them in Javascript yet, possibly because a JS object is quite close to an enum. However, when we write TS code, the enum informs us only about the readonly status, something we cannot simply accomplish from the object.

Conclusion

  • The Type System in typescript represents the many types of values that the language supports.
  • Before the software stores or manipulates the provided values, the Type System validates them.
  • A union in typescript stores the value of one or more data type variables.
  • Only the data types defined in the union in typescript can be assigned to the variable. Otherwise, a compilation error will be generated.
  • Union in typescript can also be used to pass function arguments and arrays.
  • Enums is one of several TypeScript features that are not a JavaScript type-level extension.
  • We can make our code more understandable by using enums to organize our constants into data structures rather than leaving them in the global area.
  • Using Enum is quite useful. However, it may result in additional expenses in some cases. It is therefore up to you to decide when to utilize Enum.