Tuples in TS

Learn via video courses
Topics Covered

Overview

At times, it may be necessary to keep a collection of values of various sorts. Arrays are ineffective for this purpose. TypeScript provides a data type called tuple that aids in this endeavor. It symbolizes a jumbled collection of values. Tuples, in other words, allow for the storage of several fields of various kinds. Functions can also take tuples as arguments.

Introduction

Tuples can take many different forms in computer science. Tuples are directly implemented as product types in most typed functional programming languages, closely related to algebraic data types, pattern matching, and destructuring assignment. Many computer languages provide an alternative to tuples called record types, which contain unordered items accessible by the label. Few computer languages, such as C structs (a struct is a composite data type declaration that establishes a physically grouped list of variables in a block of memory under one name) and Haskell records (C-structs in Haskell allow you to generate dynamically typed and properly padded C structs), combine ordered tuple product types and unordered record types into a single construct. Tuples are formally used to identify rows (records) in relational databases.

Tuples are an effective technique to store numerous values in computer programming. Tuples take less memory than arrays since they are static and cannot be changed. They are extremely adaptable since they can hold a variety of data kinds. The following is an example of a "5-tuple", or tuple with five values.

A positive integer (9), a floating point number (2022.09), a string (scaler), a character (S), and a negative integer are all part of the "pentuple" above (-2022).

Tuples are an efficient way to store data in computer programs, although they are not supported by all programming languages. Tuples are supported by Python and Java, but not by PHP or Ruby.

If a language somehow doesn't support tuples, the closest option is an immutable array, which cannot be updated.

Tuples in TypeScript

Tuple is a new data type introduced by TypeScript. Tuples in Typescript can have two distinct data types as values.

We already know that an array can contain several values of the same data type. However, there are occasions when we need to keep a collection of values of various data kinds in a single variable. Arrays do not provide this capability, but TypeScript offers a data type called Tuple that does. A Tuple in typescript is an array that stores numerous fields of various data kinds. Structures in the C programming language are analogous.

As we know, an array consists of values of homogenous (same) kinds, but when we need to store a collection of data of diverse types in a single variable, we will use Tuples in Typescript. They behave similarly to structures in C programming and may be supplied as elements in a function call. Tuples in typescript can include one or more types of data (like a number with string or string with a number and so on).

In abstract mathematics, the term tuple is used to indicate a multi-dimensional coordinate system.

Tuples in typescript are not accessible as data types in JavaScript, but they are in TypeScript.

A tuple in typescript is a data type that may be used in the same way as any other variable. It represents a diverse set of values and may be supplied as arguments in a function call. A multidimensional coordinate system is denoted by the term tuple in abstract mathematics. Tuples in typescript are not data types in JavaScript, but they are in TypeScript. The order of the items of a tuple is critical.

Syntax

Consider the following integer, string, and tuple variable examples.

Example

Output:

In Typescript, you may declare and initialize a tuple individually by defining it as an empty tuple first.

Example:

General Operations on Tuples

We will see Some general operations on tuple now which includes the following:

  • Declaring and initialization tuples
  • Accessing tuple values using index
  • Push and Pop
  • Updating Tuple Elements
  • Clearing the values in a Tuple
  • Passing a tuple to a function

Declaring and Initialization Tuples

To create or initialize a tuple in typescript, define it as a variable and then load the fields into it with the assignment operator (=), as seen below:

The term let is a reserved Word. tuple_name is the name of the tuple that will be used to refer to it later in the program. The nth field value is represented by valuen.

Accessing Tuple Values Using Index

We may read or access the fields of a tuple in typescript, which is the same as an array, using index basis. An index, too, begins at zero. Tuple in typescript values are referred to as items. Tuples are based on indexes. This means that entries in a tuple can be retrieved through their numeric index. The index of a tuple item starts at zero and goes up to n-1 (where n is the size of the tuple).

Syntax

Example: Simple Tuple

A tuple, first_tuple, is declared in the previous example. The tuple comprises values of the numeric and string kinds.

It will create identical code in JavaScript when compiled.

Output:

Example: Empty Tuple

It will create identical code in JavaScript when compiled.

Output :

Tuple Operations

Tuples in TypeScript offer a variety of actions such as adding a new item, deleting an item from the tuple, and so on.

Example:

It will create identical code in JavaScript when compiled.

Output:

A tuple can do two operations:

  1. Push()
  2. Pop()

Push()

The push operation is used to add a tuple element in the typescript.

Example:

It will create identical code in JavaScript when compiled.

Output:

Pop()

The pop procedure is used to delete an element from the tuple in typescript.

Example:

It will create identical code in JavaScript when compiled.

Output:

Updating Tuple Elements

Tuples are changeable, which implies that their values may be updated or changed. To change the fields of a Tuple, we must utilize the field index and the assignment operator. The following example will help us comprehend it.

Example:

When compiled, it will generate the same code in JavaScript.

Output :

Clearing the Values in a Tuple

The tuple variable cannot be deleted, although its fields can be cleaned. To clear the fields of a tuple, assign it to an empty set of tuple fields, as illustrated in the example below.

Example:

When compiled, it will generate the same code in JavaScript.

Output:

Tuple Deconstruction

Destructuring allows us to disassemble an entity's structure. In the context of a tuple, TypeScript utilized destructuring.

Example:

It will create identical code in JavaScript when compiled. Output:

Passing a Tuple to a Function

We may send a tuple to functions, as illustrated in the example below.

Example:

It will create identical code in JavaScript when compiled.

Output:

Typed Array

A tuple is a typed array with a fixed length and different types for each index. Tuples are useful because they allow each array element to have a known kind of value. To define a tuple, give the type of each array element:

Example:

We have a number, a boolean, and a string, as you can see. But what if we try to arrange them in the wrong order:

Example:

Readonly Tuples

Making your tuple read-only is a smart idea. Tuples' starting values have only clearly specified types:

Example:

Output :

You notice the changed value. Tuples' starting values have only clearly specified types:

Example:

TypeScript: Arrays and Tuples

Dealing with arrays in TypeScript is similar to working with arrays in JavaScript. The same fundamental ideas and methodologies apply, such as iterations, filtering, reducing, pushing, pulling, and so on. The key difference with TS is the limitation on what data types we may have in an array. If we indicate that an array should only contain texts, we will see an error notice if we attempt to add a number to the same array.

Inference and Annotations

The inference technique also works well with arrays. When an array is populated with values, the proper types are automatically allocated, and no manual annotations are required. In the following example, an array contains primitive string types. Hovering over the variable reveals an annotation with the right types:

Why do we need to manually annotate if the inference algorithm works so well? One example is when we need to initialize an array before pushing values into it. Because the inference does not know what data type entries would be added in the future when creating an empty array, it assigns the error-prone any[] type:

Syntax:

The array annotation syntax is a value type followed by brackets: Type[]. Here are some instances of arrays with various value types:

When an array is confined to a specific kind of value, attempting to assign a different type results in an error message:

When dealing with array methods like map, filter, or reduce, you benefit from type inference and autocomplete. If we traverse an array of strings, each array element in the method will be assigned to a string and will receive autocomplete for a whole set of String attributes.

Tuple

Tuples are like arrays, but more exact. Tuples contain a certain number of items. Tuples can also contain a variety of constituent types, such as [string, number, string[]]. It is a TypeScript feature that allows you to limit the number and type of values in an array. It has the signature: [Type], which differs significantly from an array: Type[].

Let us define an array as a tuple of string and number:

This tuple always has a fixed number of values of two, with a string coming first and a number coming second. If you change the order of the types or the number of values, TS will give an error. Tuples are difficult to grasp. When you read code, you don't see a context for a tuple containing a string and a number. For example, given a tuple ['Sahil', 49], you may reasonably assume that the first item is a name, but what does 49 represent? It might be your weight or your shoe size. So, for context, it is preferable to use an object: name: 'Sahil,' age: 49.

Tuples have certain specific instances. When working with CSV files, for example. Tuples are a simple way to express a row entry.

Conclusion (in points)

  • TypeScript was designed to supplement JavaScript rather than replace it. In the future, their features may become extremely similar, with TypeScript being the statically-typed option.
  • A tuple is a data type that may be utilized just like any other variable. It represents a wide range of values that can be sent as parameters to a function call.
  • With sample TypeScript programs, we learned how to create a tuple, read field members from it, update the fields on the fly, and clear the fields if required.
  • Using arrays in TypeScript is comparable to using arrays in JavaScript. Iterations, filtering, reducing, pushing, pulling, and other fundamental notions and procedures are all applicable.
  • Tuples are more precise than arrays, tuples have a set number of elements.
  • Manual annotations are not required when expressing an array with known values; the inference system will suffice.