Introduction
TypeScript, a superscript of JavaScript, offers static typing capabilities that help developers ensure type safety. One scenario where TypeScript shines is in defining arrays with multiple types, also known as ‘tuples’. This tutorial will guide you through using such feature-rich structures in TypeScript.
Type Basics
Before jumping into multi-type arrays, let’s quickly review TypeScript’s fundamental type annotations. In TypeScript, you can define an array of single type elements as follows:
let fruits: string[] = ['Apple', 'Banana', 'Cherry'];
However, in some cases, you need an array to store elements of various types.
Defining Multi-Type Arrays
To define an array with multiple types, you use the tuple type in TypeScript:
let mixedArray: [string, number, boolean] = ['Hello', 42, true];
This indicates that the first element must be a string, the second a number, and the third a boolean.
Basic Usage
In its simplest form, you could use such an array as follows:
let person: [string, number] = ['Alex', 30];
console.log(person[0]); // Output: Alex
console.log(person[1]); // Output: 30
Adding Optional Types
Optionally, you can allow undefined values using the ‘?’ operator to indicate optional elements:
let optionalTuple: [string, number, boolean?] = ['Tree', 10];
Array of Tuples
When you have an array where each item is a tuple of the same structure, you can define it as follows:
let employeeData: [string, number, boolean][] = [
['Alice', 28, true],
['Bob', 35, false]
];
Variadic Tuple Types
With TypeScript 4.0 and later, you have the option to define variadic tuple types using the spread operator:
type StringNumberBooleans = [string, number, ...boolean[]];
let data: StringNumberBooleans = ['Sample', 10, true, false, true];
Tuple Operations
Working with TypeScript tuples involves understanding how to manipulate these structures.
Accessing Tuple Elements
Accessing elements in a tuple is akin to array access:
let firstElement = mixedArray[0]; // string
let secondElement = mixedArray[1]; // number
Adding and Removing Elements
Mutating a tuple should usually align with its defined structure:
// Correctly adding elements
optionalTuple.push(100);
// Incorrectly adding elements - would throw an error during compilation
optionalTuple.push('New string');
Advanced Tuple Type Patterns
More complex scenarios bring out the power of tuples with multiple types in TypeScript.
Read-Only Tuples
You can also define tuples that are not mutable using the ‘readonly’ keyword:
let fixedTuple: readonly [string, number] = ['Immutable', 10];
// fixedTuple.push(20); // Error!
Tuple with Rest Parameters
Functions can take advantage of Tuple types with rest parameters.
function logItems(...items: [string, number, boolean]) {
items.forEach(item => console.log(item));
}
logItems('Test', 42, true);
Generics and Tuples
Generics offer a way to create reusable component types. They work with tuples too:
function pair<T, U>(a: T, b: U): [T, U] {
return [a, b];
}
let stringNumberPair = pair('One', 1);
Practical Application
This section covers common use-cases for tuples in real-life development.
Returning multiple Values
Often you want to return multiple values from a function:
function getStats(input: number[]): [number, number, number] {
const total = input.reduce((acc, val) => acc + val, 0);
const count = input.length;
const average = total / count;
return [total, count, average];
}
CSV File Parsing
Parsing CSV files often involves working with different data types, and tuples can fit this scenario quite well:
// Assume a CSV line: Name, Age, HasDriverLicence
let csvData: [string, number, boolean] = parseCSVLine('John,30,true');
Conclusion
Using multiple types in a TypeScript array utilizes the power of tuples, providing several benefits such as type safety, clarity in function return types, and flexible array-like usage. Variadic tuples and tuple generics open even more possibilities, cementing TypeScript’s reputation as a powerful tool for developers.