YouTip LogoYouTip

Ts Tuple

We know that the data types of elements in an array are generally the same (arrays of type `any[]` can be different). If you need to store elements of different data types, you need to use a tuple. A tuple in TypeScript is a special type of array that allows storing elements of different types. Unlike a regular array, each element in a tuple has a specific type and position. Tuples are often used to represent data structures with a fixed length and known types for each element. The syntax for creating a tuple is as follows: ```typescript let tuple: [Type1, Type2, Type3, ...]; ### Example Declare and initialize a tuple: ```typescript let mytuple: [number, string]; mytuple = [42, "Tutorial"]; In the example above, `mytuple` is a tuple containing one element of type `number` and one of type `string`. ### Accessing Tuples Elements in a tuple are accessed using an index. The index of the first element is 0, the second is 1, and so on, with the nth element at index n-1. The syntax is: ```typescript tuple_name ### Example The following example defines a tuple containing elements of two types: number and string. ## TypeScript ```typescript let mytuple: [number, string, boolean] = [42, "Tutorial", true]; let num = mytuple; let str = mytuple; let bool = mytuple; console.log(num); console.log(str); console.log(bool); Compiling the above code yields the following JavaScript code: ## JavaScript ```javascript var mytuple = [42, "Tutorial", true]; var num = mytuple; var str = mytuple; var bool = mytuple; console.log(num); console.log(str); console.log(bool); The output is: 42 Tutorial true * * * ## Tuple Operations We can use the following two functions to add or remove elements from a tuple: * `push()` adds an element to the tuple, 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, but 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 ```typescript var tuple = [42, "Hello"]; tuple.push("World"); console.log(tuple); Compiling the above code yields the following JavaScript code: ## JavaScript ```javascript var tuple = [42, "Hello"]; tuple.push("World"); console.log(tuple); The output 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 is inferred based on the tuple's defined types. ### Example ```typescript let tuple: [number, string, boolean] = [42, "Hello", true]; // Remove the last element let lastElement = tuple.pop(); console.log(lastElement); // Output: true console.log(tuple); // Output: [42, "Hello"] * * * ## Updating Tuples Tuples are mutable, meaning we can perform update operations on them: ## TypeScript ```typescript var mytuple = [42, "Tutorial", "Taobao", "Google"]; console.log("The first element of the tuple is:" + mytuple); mytuple = 121; console.log("The first element of the tuple is updated to:" + mytuple); Compiling the above code yields the following JavaScript code: ## JavaScript ```javascript var mytuple = [42, "Tutorial", "Taobao", "Google"]; console.log("The first element of the tuple is:" + mytuple); mytuple = 121; console.log("The first element of the tuple is updated to:" + mytuple); The output is: The first element of the tuple is: 42 The first element of the tuple is updated to: 121 * * * ## Destructuring Tuples We can also assign tuple elements to variables, as shown below: ## TypeScript ```typescript let a: [number, string, boolean] = [42, "Hello", true]; var [b, c] = a; console.log(b); console.log(c); Compiling the above code yields the following JavaScript code: ## JavaScript ```javascript var a = [42, "Hello", true]; var b = a, c = a; console.log(b); console.log(c); The output is: 42 Hello * * * ## Using Labeled Tuples TypeScript also allows adding labels to each element in a tuple, making the tuple's meaning clearer: ```typescript let tuple: [id: number, name: string] = [1, "John"]; In this example, `id` and `name` are labels for the tuple, which can make the code more readable. * * * ## Practical Applications of Tuples Tuples are commonly used in scenarios where a function returns multiple values, or to represent data with a fixed structure, such as: ### Example ```typescript function getUserInfo(): [number, string] { return [1, "John Doe"]; } const [userId, userName] = getUserInfo(); console.log(userId); // Output: 1 console.log(userName); // Output: John Doe * * * ## Type Inference for Tuples TypeScript can automatically infer the type of a tuple based on its elements: ```typescript let tuple = [42, "Hello"] as const; // Tuple type: [42, "Hello"] With the `as const` assertion, TypeScript treats this tuple as an immutable constant tuple. * * * ## Concatenating Tuples Tuples can be concatenated using the array's `concat` method, but note that the result is a regular array, not a tuple. ### Example ```typescript let tuple1: [number, string] = [42, "Hello"]; let tuple2: [boolean, number] = [true, 100]; let result = tuple1.concat(tuple2); // 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 slice a tuple, returning a new array. ### Example ```typescript let tuple: [number, string, boolean] = [42, "Hello", true]; let sliced = tuple.slice(1); // Slice from index 1 console.log(sliced); // Output: ["Hello", true] * * * ## Iterating Over Tuples You can iterate over the elements of a tuple using a `for...of` loop or the `forEach` method. ### Example ```typescript let tuple: [number, string, boolean] = [42, "Hello", true]; // Using a for...of loop for (let item of tuple) { console.log(item); } // Using the forEach method tuple.forEach(item => console.log(item)); * * * ## Converting to a Regular Array Although a tuple is a fixed-length, fixed-type array, it can be converted to a regular array for further processing using `Array.prototype` methods. ### Example ```typescript let tuple: [number, string, boolean] = [42, "Hello", true]; // 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 ```typescript let tuple1: [number, string] = [42, "Hello"]; let tuple2: = ; let extendedTuple: [number, string, ...typeof tuple2] = [42, "Hello", ...tuple2]; console.log(extendedTuple); // Output: [42, "Hello", true]
← Ts InterfaceTs String β†’