TypeScript's tuple types offer a powerful way to represent fixed-length arrays with specific types at each position. They allow you to store related but distinct data within a single array, making your code cleaner and more predictable. In this tutorial, we’ll cover everything you need to know about using tuples in TypeScript, from basic syntax to advanced features, along with practical examples.
In TypeScript, tuples are a type of array that lets you define not only the number of elements but also the type of each element. This feature is useful when working with structured data where each position in the array has a specific meaning and type. Tuples enhance type safety, helping you ensure that each element is in the correct position and format.
A tuple in TypeScript is a fixed-length array with specific types for each position. Unlike regular arrays, which allow elements of any type, tuples enforce strict types on each element and the length of the array. This is especially useful when you want to group related values with different types in a single structure.
let person: [string, number];
person = ["Alice", 30]; // Valid
// person = [30, "Alice"]; // Error: Type 'number' is not assignable to type 'string' at position 0
In this example, person
is a tuple where the first element is a string
and the second element is a number
. TypeScript will enforce these types, ensuring the structure remains consistent.
To declare a tuple type, specify the types of each element inside square brackets []
.
let product: [string, number, boolean] = ["Laptop", 1200, true];
In this example:
string
representing the product name.number
representing the price.boolean
indicating availability.let coordinates: [number, number] = [10, 20];
// coordinates = [20, "30"]; // Error: Type 'string' is not assignable to type 'number'
TypeScript will ensure that only numbers can be assigned to coordinates
, making the data structure reliable.
You can access and modify tuple elements in the same way as with regular arrays, using index notation.
let user: [string, number] = ["Alice", 25];
console.log(user[0]); // Output: Alice
console.log(user[1]); // Output: 25
// Modifying elements
user[1] = 26;
console.log(user[1]); // Output: 26
While you can modify elements in a tuple, TypeScript will enforce the type for each position. For instance, you can’t assign a string
to user[1]
because it’s typed as a number
.
TypeScript allows you to create tuples with optional and readonly elements, providing flexibility while maintaining control over your data structures.
Optional elements allow you to omit the last element of a tuple if it’s not needed. To mark an element as optional, add a ?
after its type.
let userData: [string, number, boolean?];
userData = ["Alice", 30]; // Valid
userData = ["Alice", 30, true]; // Also valid
In this example, userData
can either have two or three elements, with the last boolean
element being optional.
Readonly
tuples prevent modification of their elements, ensuring the data remains unchanged after initialization.
let position: readonly [number, number] = [0, 0];
// position[0] = 5; // Error: Cannot assign to '0' because it is a read-only property
Readonly tuples are especially useful for data that shouldn’t be altered, like fixed coordinates or default settings.
TypeScript allows tuples to contain rest elements, making it possible to have variable-length tuples where certain elements have a fixed type. Rest elements are defined by using the ...
syntax.
type StringNumberTuple = [string, ...number[]];
let data: StringNumberTuple = ["Alice", 1, 2, 3];
console.log(data); // Output: ["Alice", 1, 2, 3]
In this example, data
must start with a string
, followed by any number of number
elements. Rest elements are useful for representing structured data where some elements are fixed, but others can vary.
Geographic coordinates can be represented as tuples, where each coordinate is a fixed pair of numbers (latitude and longitude).
type Coordinates = [number, number];
let location: Coordinates = [40.7128, -74.0060]; // New York City coordinates
function printLocation(coord: Coordinates): void {
console.log(`Latitude: ${coord[0]}, Longitude: ${coord[1]}`);
}
printLocation(location); // Output: Latitude: 40.7128, Longitude: -74.0060
In this example:
Coordinates
is a tuple that strictly holds two number values.printLocation
function ensures the format is consistent, making it easy to work with geographic data.Tuples are perfect for representing key-value pairs, especially when working with structured data, like configuration settings.
type KeyValuePair = [string, string];
let config: KeyValuePair = ["theme", "dark"];
function printConfig(setting: KeyValuePair): void {
console.log(`Setting: ${setting[0]}, Value: ${setting[1]}`);
}
printConfig(config); // Output: Setting: theme, Value: dark
In this example:
KeyValuePair
is a tuple that ensures each configuration setting has a string
key and a string
value.When working with API responses, tuples can help define the structure of HTTP status codes and response messages.
type HttpResponse = [number, string];
let response: HttpResponse = [200, "OK"];
function handleResponse(response: HttpResponse): void {
console.log(`Status: ${response[0]}, Message: ${response[1]}`);
}
handleResponse(response); // Output: Status: 200, Message: OK
In this example:
HttpResponse
is a tuple with a number status code and a string
message.TypeScript tuples are a powerful tool for representing structured, fixed-length arrays where each element has a distinct type. By enforcing specific types and lengths, tuples make your code more predictable and reduce runtime errors. This guide covered the essentials of declaring, accessing, and using tuples in TypeScript, as well as advanced concepts like optional, readonly, and rest elements. With tuples, you can create code that is both structured and flexible, ideal for working with consistent, predictable data in TypeScript.