TypeScript Tuples
We know that the data types of elements in an array are generally the same (arrays of type any[] can be different). If the stored elements have different data types, you need to use tuples.
A tuple in TypeScript is a special type of array that allows storing elements of different types in the array. Unlike ordinary arrays, each element in a tuple has a clear type and position. Tuples can be used in many scenarios to represent data structures with fixed length and known element types.
The syntax for creating a tuple is as follows:
let tuple: [类型1, 类型2, 类型3, ...];
Example
Declare a tuple and initialize it:
let mytuple: [number, string]; mytuple = [42,"Example"];
In the above example, mytuple is a tuple that contains an element of type number and an element of type string.
Accessing Tuples
Elements in a tuple are accessed using indexes. The index of the first element is 0, the second is 1, and so on, the nth is n-1. The syntax is as follows:
tuple_name[index]
Example
The following example defines a tuple that contains two types of elements: numbers and strings.
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
42 Example true
Tuple Operations
We can use the following two functions to add new elements to or remove elements from a tuple:
push() adds an element to the tuple, appending it at the end.
pop() removes an element (the last one) from the tuple and returns the removed element.
The push method can add an element to the end of a tuple, and the type must conform to the type constraints defined in the tuple. If it exceeds the tuple's type constraints, TypeScript will report an error.
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
[ 42, 'Hello', 'World' ]
The pop method removes an element from the end of a tuple and returns that element. The type of the returned element will be inferred based on the tuple's defined types.
Example
// Remove the last element
let lastElement = tuple.pop();
console.log(lastElement); // Output: true
console.log(tuple); // Output: [42, "Hello"]
Updating Tuples
Tuples are mutable, which means we can perform update operations on tuples:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
元组的第一个元素为:42 元组中的第一个元素更新为:121
Destructuring Tuples
We can also assign tuple elements to variables, as shown below:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
42 Hello
Using Labeled Tuples
TypeScript also allows adding labels to each element in a tuple, which makes the meaning of the tuple clearer:
let tuple: [id: number, name: string] = [1, "John"];
In this example, id and name are labels of the tuple, which can make the code more readable.
Practical Applications of Tuples
Tuples are often used in scenarios where a function returns multiple values, or to represent data with a certain fixed structure, for example:
Example
return [1, "John Doe"];
}
const [userId, userName] = getUserInfo();
console.log(userId); // Output: 1
console.log(userName); // Output: John Doe
Type Inference of Tuples
TypeScript can automatically infer the type of a tuple based on the elements of the array:
let tuple = [42, "Hello"] as const; // 元组类型:[42, "Hello"]
Through the as const assertion, TypeScript will treat this tuple as an immutable constant tuple.
Concatenating Tuples
Tuples can be concatenated using the array's concat method, but note that the result after concatenation is an ordinary array, not a tuple.
Example
let tuple2: [boolean, number] = [true, 100];
let result = tuple1.concat(tuple2); // The result is an array: [42, "Hello", true, 100]
console.log(result); // Output: [42, "Hello", true, 100]
Slicing Tuples
You can use the array's slice method to perform slicing operations on a tuple, returning a new array.
Example
let sliced = tuple.slice(1); // Slice starting from index 1
console.log(sliced); // Output: ["Hello", true]
Iterating Over Tuples
You can use a for...of loop or the forEach method to iterate over the elements in a tuple.
Example
// Using for...of loop
for (let item of tuple) {
console.log(item);
}
// Using forEach method
tuple.forEach(item => console.log(item));
Converting to a Regular Array
Although a tuple is an array with fixed length and fixed types, you can convert it to an ordinary array through methods of Array.prototype for further processing.
Example
// Convert to an array and use array methods
let array = Array.from(tuple);
array.push("New Element");
console.log(array); // Output: [42, "Hello", true, "New Element"]
Extending Tuples
Using the rest operator, you can easily merge multiple tuples into a new tuple:
Example
let tuple2: [boolean] = [true];
let extendedTuple: [number, string, ...typeof tuple2] = [42, "Hello", ...tuple2];
console.log(extendedTuple); // Output: [42, "Hello", true]