
- TypeScript - Home
- TypeScript - Roadmap
- TypeScript - Overview
- TypeScript - Environment Setup
- TypeScript - Basic Syntax
- TypeScript vs. JavaScript
- TypeScript - Features
- TypeScript - Variables
- TypeScript - let & const
- TypeScript - Operators
- TypeScript - Types
- TypeScript - Type Annotations
- TypeScript - Type Inference
- TypeScript - Numbers
- TypeScript - Strings
- TypeScript - Boolean
- TypeScript - Arrays
- TypeScript - Tuples
- TypeScript - Enums
- TypeScript - Any
- TypeScript - Never
- TypeScript - Union
- TypeScript - Literal Types
- TypeScript - Symbols
- TypeScript - null vs. undefined
- TypeScript - Type Aliases
- TypeScript Control Flow
- TypeScript - Decision Making
- TypeScript - If Statement
- TypeScript - If Else Statement
- TypeScript - Nested If Statements
- TypeScript - Switch Statement
- TypeScript - Loops
- TypeScript - For Loop
- TypeScript - While Loop
- TypeScript - Do While Loop
- TypeScript Functions
- TypeScript - Functions
- TypeScript - Function Types
- TypeScript - Optional Parameters
- TypeScript - Default Parameters
- TypeScript - Anonymous Functions
- TypeScript - Function Constructor
- TypeScript - Rest Parameter
- TypeScript - Parameter Destructuring
- TypeScript - Arrow Functions
- TypeScript Interfaces
- TypeScript - Interfaces
- TypeScript - Extending Interfaces
- TypeScript Classes and Objects
- TypeScript - Classes
- TypeScript - Objects
- TypeScript - Access Modifiers
- TypeScript - Readonly Properties
- TypeScript - Inheritance
- TypeScript - Static Methods and Properties
- TypeScript - Abstract Classes
- TypeScript - Accessors
- TypeScript - Duck-Typing
- TypeScript Advanced Types
- TypeScript - Intersection Types
- TypeScript - Type Guards
- TypeScript - Type Assertions
- TypeScript Type Manipulation
- TypeScript - Creating Types from Types
- TypeScript - Keyof Type Operator
- TypeScript - Typeof Type Operator
- TypeScript - Indexed Access Types
- TypeScript - Conditional Types
- TypeScript - Mapped Types
- TypeScript - Template Literal Types
- TypeScript Generics
- TypeScript - Generics
- TypeScript - Generic Constraints
- TypeScript - Generic Interfaces
- TypeScript - Generic Classes
- TypeScript Miscellaneous
- TypeScript - Triple-Slash Directives
- TypeScript - Namespaces
- TypeScript - Modules
- TypeScript - Ambients
- TypeScript - Decorators
- TypeScript - Type Compatibility
- TypeScript - Date Object
- TypeScript - Iterators and Generators
- TypeScript - Mixins
- TypeScript - Utility Types
- TypeScript - Boxing and Unboxing
- TypeScript - tsconfig.json
- From JavaScript To TypeScript
- TypeScript Useful Resources
- TypeScript - Quick Guide
- TypeScript - Cheatsheet
- TypeScript - Useful Resources
- TypeScript - Discussion
TypeScript - Tuples
At times, there might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose.
It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions.
Syntax
We can create a tuple using JavaScripts array syntax:
const tupleName = [value1, value2, value3, ...valueN]
But we need to declare its type as a tuple.
const tupleName: [type1, type2, type3, ...typeN] = [value1, value2, value3, ...valueN]
For Example
const myTuple: [number, string] = [10,"Hello"];
You can define a tuple first and then initialize,
let myTuple: [number, string]; // declaring the tuple myTuple = [10, "Hello"]; // initializing the tuple
Make sure, the const tuple declared must be initialized.
You can also declare an empty tuple in Typescript and choose to initialize it later.
var myTuple = []; myTuple[0] = 10; myTuple[1] = "Hello";
Accessing Values in Tuples
Tuple values are individually called items. Tuples are index based. This means that items in a tuple can be accessed using their corresponding numeric index. Tuple items index starts from zero and extends up to n-1(where n is the tuples size).
Syntax
Following is the syntax to access the values in a tuple using its index −
tupleName[index]
Example: Simple Tuple
var myTuple: [number, string] = [10,"Hello"]; //create a tuple console.log(myTuple[0]) console.log(myTuple[1])
In the above example, a tuple, myTuple, is declared. The tuple contains values of numeric and string types respectively.
On compiling, it will generate the following code in JavaScript.
var myTuple = [10, "Hello"]; //create a tuple console.log(myTuple[0]); console.log(myTuple[1]);
Its output is as follows −
10 Hello
Example: Empty Tuple
We can declare an empty tuple as follows and then initialize it.
var tup = [] tup[0] = 12 tup[1] = 23 console.log(tup[0]) console.log(tup[1])
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
12 23
Tuple Operations
Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc.
Example
var myTuple: [number, string, string, string]; myTuple = [10,"Hello","World","typeScript"]; console.log("Items before push " + myTuple.length) myTuple.push(12) // append value to the tuple console.log("Items after push " + myTuple.length) console.log("Items before pop " + myTuple.length) // removes and returns the last item console.log(myTuple.pop() + " popped from the tuple") console.log("Items after pop " + myTuple.length)
The push() appends an item to the tuple
The pop() removes and returns the last value in the tuple
On compiling, it will generate the following code in JavaScript.
var myTuple; myTuple = [10, "Hello", "World", "typeScript"]; console.log("Items before push " + myTuple.length); myTuple.push(12); // append value to the tuple console.log("Items after push " + myTuple.length); console.log("Items before pop " + myTuple.length); // removes and returns the last item console.log(myTuple.pop() + " popped from the tuple"); console.log("Items after pop " + myTuple.length);
The output of the above code is as follows −
Items before push 4 Items after push 5 Items before pop 5 12 popped from the tuple Items after pop 4
Updating Tuples
Tuples are mutable which means you can update or change the values of tuple elements.
Example
var myTuple: [number, string, string, string]; // define tuple myTuple = [10,"Hello","World","typeScript"]; // initialize tuple console.log("Tuple value at index 0 " + myTuple[0]) //update a tuple element myTuple[0] = 121 console.log("Tuple value at index 0 changed to " + myTuple[0])
On compiling, it will generate the following code in JavaScript.
var myTuple; // define tuple myTuple = [10, "Hello", "World", "typeScript"]; // initialize tuple console.log("Tuple value at index 0 " + myTuple[0]); //update a tuple element myTuple[0] = 121; console.log("Tuple value at index 0 changed to " + myTuple[0]);
The output of the above code is as follows −
Tuple value at index 0 10 Tuple value at index 0 changed to 121
Destructuring a Tuple
Destructuring refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of a tuple.
Example
var a: [number, string] = [10,"hello"]; var [b, c] = a; console.log( b ); console.log( c );
On compiling, it will generate following JavaScript code.
var a = [10, "hello"]; var b = a[0], c = a[1]; console.log(b); console.log(c);
Its output is as follows −
10 hello
Function Parameters and Tuple Types
We can define a function to accept explicitly a tuple type. So while calling the function we pass the tuple as argument.
Example
function processData(data: [string, number]): void { const [name, age] = data; console.log(`Name: ${name}, Age: ${age}`); } let data: [string, number] = ["John", 32] processData(data);
We defined here a function processData() that accepts a parameter of tuple type. Inside the function we use tuple destructuring to get the constituent elements. We call the function passing a tuple as argument.
On compiling, it will generate the following JavaScript code.
function processData(data) { const [name, age] = data; console.log(`Name: ${name}, Age: ${age}`); } let data = ["John", 32]; processData(data);
The output of the above code is as follows −
Name: John, Age: 32