Typescript Arrays And Tuples Complete Guide
Understanding the Core Concepts of TypeScript Arrays and Tuples
TypeScript Arrays
Arrays in TypeScript are similar to JavaScript arrays but come with the added benefit of type annotations which ensure that the array holds elements of the same specified type.
Important Information
Typed Arrays: You can specify the type of elements that an array will hold. For example, an array is meant to store only numbers, strings, or objects.
let numbers: number[] = [1, 2, 3]; let names: string[] = ["Alice", "Bob"];
Generic Array Types: You can achieve the same result with generic syntax using
Array<T>
.let numbers: Array<number> = [10, 20, 30];
Readonly Arrays: These are arrays where you cannot add or remove elements. The type
ReadonlyArray<T>
allows you to specify an array as readonly.let numbers: ReadonlyArray<number> = [4, 5, 6]; // or with the shorthand syntax let numbers: readonly number[] = [4, 5, 6];
Multidimensional Arrays: Arrays in TypeScript can be multidimensional, allowing for a nested structure. Commonly used for matrix representations.
let matrix: number[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
Array Methods: TypeScript supports all existing JavaScript array methods, which operate in a type-safe manner.
let fruits: string[] = ["Apple", "Banana", "Cherry"]; fruits.push("Date"); // Add element to end fruits.pop(); // Remove last element fruits.indexOf("Banana"); // Return the index of Banana
Type Inference: When defining arrays, TypeScript infers the type from the provided values, but it's good practice to explicitly specify the types.
let numbers = [1, 2, 3]; // 'numbers' type is inferred to be 'number[]'
TypeScript Tuples
Tuples are a special kind of array found in TypeScript where each element has a fixed type. This means that an array is declared with a known length and types for each position in the array.
Important Information
Tuple Declaration: You declare a tuple by specifying the types of all its elements.
let point: [number, number] = [10, 20];
Accessing Tuple Elements: Elements within a tuple can be accessed using bracket notation, just like in JavaScript arrays.
let point: [number, number] = [10, 20]; console.log(point[0]); // Output: 10 (X coordinate) console.log(point[1]); // Output: 20 (Y coordinate)
Tuples with Optional Properties: Starting in TypeScript 3.0, you can create tuples with optional properties.
let pointWithOptional?: [number, number?, "fixed"?] = [5];
Rest Elements in Tuples: Introduced in TypeScript 3.0, allows defining tuples with any number of trailing elements.
type StringNumberBooleans = [string, number, ...boolean[]];
Tuple Type with Read-only Modifier: Ensures that the contents of the tuple can’t be modified.
let point: readonly [number, number] = [50, 60]; // point[0] = 100; // Error, cannot assign to this property
Destructuring Tuples: Same as for destructuring regular arrays - you can unpack the values into individual variables.
const person: [string, number] = ["Jane", 27]; const [name, age] = person; console.log(name); // Output: Jane console.log(age); // Output: 27
Tuple Type Inference: TypeScript can infer the tuple types based on the assigned values.
let myTuple = [10, "Hello", true]; // 'myTuple' type is inferred to be '[number, string, boolean]'
Usage Scenarios: Tuples are particularly useful when returning multiple, related values from a function.
function getCoordinates(): [number, number] { return [150, 250]; } let coordinates = getCoordinates(); coordinates[0] = 350; coordinates[1] = 450;
Key Differences Between Arrays and Tuples
- Length: Arrays can be of any length whereas tuples have a fixed number of elements.
- Element Types: Arrays are generally used for homogeneous data (all elements of the same type) whereas tuples can contain heterogeneous data (elements of different types).
- Immutability: While Arrays can be mutable, tuples can have both mutable and immutable variants using the
readonly
modifier.
Additional Tips
Union Types in Tuples: You can create tuples where some elements are of a union type.
type Point = [number, number | "auto"]; // X can be a number, Y can be either a number or "auto"
Tuple Length Property: TypeScript 4.0 introduced a new feature called the Tuple length property, enabling compile-time computation of array length.
Online Code run
Step-by-Step Guide: How to Implement TypeScript Arrays and Tuples
Understanding TypeScript Arrays
In TypeScript, arrays can be declared in two different ways: using the type followed by []
, or using a generic array type, Array<type>
.
1. Declaring an Array
Step 1: Choose your declaration style.
You can use either the type with square brackets []
or the Array<type>
syntax.
Example 1.a: Using number[]
let numbers: number[] = [1, 2, 3, 4];
Explanation:
This declares an array named numbers
where all elements must be of type number
.
Example 1.b: Using Array<number>
let numbers: Array<number> = [1, 2, 3, 4];
Explanation:
This declares an equivalent array using the generic array type Array<number>
.
2. Accessing Array Elements
Arrays in TypeScript are zero-indexed, just like in JavaScript.
Example 2: Accessing Elements
let colors: string[] = ["red", "green", "blue"];
let firstColor = colors[0]; // "red"
let secondColor = colors[1]; // "green"
Explanation:
This accesses the first and second elements of the colors
array.
3. Adding/Modifying Elements
You can add new elements to an array or modify existing ones.
Example 3.a: Adding Elements
let fruits: string[] = ["apple", "banana"];
fruits.push("orange"); // ["apple", "banana", "orange"]
Explanation:
The push
method adds a new element at the end of the fruits
array.
Example 3.b: Modifying Elements
let animals: string[] = ["dog", "cat"];
animals[1] = "fish"; // ["dog", "fish"]
Explanation:
This modifies the second element (index 1) of the animals
array from "cat"
to "fish"
.
Understanding TypeScript Tuples
Tuples are a feature introduced in TypeScript that allow you to express an array where the type of a fixed number of elements is known, but need not be the same.
1. Declaring a Tuple
You specify the type for each element inside square brackets []
, separated by commas.
Example 1: Declaration of a Tuple
let person: [string, number];
person = ["John Doe", 30];
Explanation:
This declares a tuple person
where the first element is a string
and the second element is a number
. The order and types must match exactly.
2. Accessing Tuple Elements
You access tuple elements just like regular arrays using their indices.
Example 2: Accessing Elements
let employee: [string, string, number];
employee = ["Jane Smith", "Developer", 50000];
let name = employee[0]; // "Jane Smith"
let position = employee[1]; // "Developer"
let salary = employee[2]; // 50000
Explanation:
This shows how you can access individual elements of the employee
tuple.
3. Modifying Tuple Elements
Similar to arrays, you can modify elements of a tuple by assigning new values to specific indices.
Example 3: Modifying Elements
let product: [string, number, boolean];
product = ["Laptop", 999.99, true];
product[1] = 899.99; // Changing the price
Explanation:
Here, we modify the second element (price) of the product
tuple from 999.99
to 899.99
.
4. Optional Tuple Elements
Starting from TypeScript 3.0, you can make tuple elements optional using question marks ?
.
Example 4: Optional Elements
let user: [string, number?, boolean?];
user = ["Alice"]; // Only the required string element
user = ["Alice", 25]; // String and optional number
user = ["Alice", 25, true]; // All elements provided
Explanation:
The user
tuple has a string element that is required, but the number and boolean elements are optional (number?
, boolean?
).
Complete Example: Working with Arrays and Tuples
Let's create a more comprehensive example that combines arrays and tuples to represent a shopping cart system.
// Define a tuple for products: [productName, price, isInStock]
type Product = [string, number, boolean];
// Array to hold multiple products
let shoppingCart: Product[] = [];
// Add products to the shopping cart
shoppingCart.push(["Apple", 0.99, true]);
shoppingCart.push(["Banana", 0.59, false]); // Out of stock
shoppingCart.push(["Orange", 1.29, true]);
// Function to display items in the shopping cart
function displayItems(cart: Product[]): void {
console.log("Items in the Shopping Cart:");
cart.forEach((item, index) => {
const [name, price, isAvailable] = item;
console.log(`${index + 1}. ${name} - $${price.toFixed(2)} - ${(isAvailable ? "In Stock" : "Out of Stock")}`);
});
}
// Call the function to display the cart
displayItems(shoppingCart);
Explanation:
Type Definition:
type Product = [string, number, boolean];
This defines a
Product
tuple with three elements:- A
string
for the product name. - A
number
for the product price. - A
boolean
indicating if the product is in stock.
- A
Array Initialization:
let shoppingCart: Product[] = [];
We declare an empty array
shoppingCart
that can holdProduct
tuples.Adding Items to the Array:
shoppingCart.push(["Apple", 0.99, true]); shoppingCart.push(["Banana", 0.59, false]); shoppingCart.push(["Orange", 1.29, true]);
Three items are added to the
shoppingCart
array using thepush
method.Function to Display Items:
function displayItems(cart: Product[]): void { console.log("Items in the Shopping Cart:"); cart.forEach((item, index) => { const [name, price, isAvailable] = item; console.log(`${index + 1}. ${name} - $${price.toFixed(2)} - ${(isAvailable ? "In Stock" : "Out of Stock")}`); }); }
- The
displayItems
function takes aProduct[]
array as its parameter. - It logs a message indicating the items in the shopping cart.
- Using the
forEach
method, it iterates over each product. - Inside the loop, tuple destructuring assigns
name
,price
, andisAvailable
variables based on the tuple elements. - Finally, it logs the details of each item in a formatted string.
- The
Calling the Function:
displayItems(shoppingCart);
This calls the
displayItems
function and passes theshoppingCart
array to it.
Output:
Items in the Shopping Cart:
1. Apple - $0.99 - In Stock
2. Banana - $0.59 - Out of Stock
3. Orange - $1.29 - In Stock
Advanced Tuple Example: Mixed Types and Optional Elements
Let's consider a more advanced scenario where we have mixed data types and optional elements in our tuples.
// Define a tuple for a user profile: [username, age, email?, isAdmin?]
type UserProfile = [string, number, string?, boolean?];
// Initialize the array with user profiles
let users: UserProfile[] = [
["Alice", 28],
["Bob", 35, "bob@example.com"],
["Charlie", 24, undefined, true], // No email, admin
["Diana", 29, "diana@example.com", false], // Email, not admin
];
// Function to display user profiles
function displayUsers(userProfiles: UserProfile[]): void {
console.log("User Profiles:");
userProfiles.forEach((profile, index) => {
const [username, age, email, isAdmin] = profile;
console.log(`User ${index + 1}:`);
console.log(`Username: ${username}`);
console.log(`Age: ${age}`);
console.log(`Email: ${email || "Not provided"}`); // Use email or default message
console.log(`Is Admin: ${isAdmin === undefined ? "No data" : isAdmin ? "Yes" : "No"}`);
console.log("-----------------------------------");
});
}
// Call the function to display user profiles
displayUsers(users);
Explanation:
Tuple Type Definition:
type UserProfile = [string, number, string?, boolean?];
string
: Username (required).number
: Age (required).string?
: Email (optional).boolean?
: IsAdmin (optional).
Array Initialization:
let users: UserProfile[] = [ ["Alice", 28], ["Bob", 35, "bob@example.com"], ["Charlie", 24, undefined, true], ["Diana", 29, "diana@example.com", false], ];
- Four user profiles are created.
- Some profiles include email and/or admin status while others do not.
Function to Display User Profiles:
function displayUsers(userProfiles: UserProfile[]): void { console.log("User Profiles:"); userProfiles.forEach((profile, index) => { const [username, age, email, isAdmin] = profile; console.log(`User ${index + 1}:`); console.log(`Username: ${username}`); console.log(`Age: ${age}`); console.log(`Email: ${email || "Not provided"}`); console.log(`Is Admin: ${isAdmin === undefined ? "No data" : isAdmin ? "Yes" : "No"}`); console.log("-----------------------------------"); }); }
- The
displayUsers
function iterates over each user profile in the array. - Tuple destructuring assigns the values to the respective variables (
username
,age
,email
,isAdmin
). - The email is displayed or a default message (
"Not provided"
) if it isundefined
. - The
isAdmin
status is checked:- If
undefined
, it logs"No data"
. - If
true
, it logs"Yes"
. - If
false
, it logs"No"
.
- If
- The
Calling the Function:
displayUsers(users);
Output:
User Profiles:
User 1:
Username: Alice
Age: 28
Email: Not provided
Is Admin: No data
-----------------------------------
User 2:
Username: Bob
Age: 35
Email: bob@example.com
Is Admin: No data
-----------------------------------
User 3:
Username: Charlie
Age: 24
Email: Not provided
Is Admin: Yes
-----------------------------------
User 4:
Username: Diana
Age: 29
Email: diana@example.com
Is Admin: No
-----------------------------------
Conclusion
- Arrays in TypeScript are typed collections of elements. You can declare them using
type[]
orArray<type>
. - Tuples provide a way to express an array where the type of a fixed number of elements is known and can differ.
- Using tuples ensures type safety for fixed-size collections of varying data types, which can be very useful in many real-world applications.
These examples should provide a solid foundation for getting started with TypeScript arrays and tuples. Happy coding!
Top 10 Interview Questions & Answers on TypeScript Arrays and Tuples
1. What are arrays in TypeScript?
Answer: In TypeScript, arrays are ordered collections that can hold zero or more elements of the same type. You can declare an array type in one of two ways:
- Using
Type[]
syntax whereType
is the type of the elements. - Using
Array<Type>
syntax.
Example:
let fruits: string[] = ["apple", "banana", "cherry"];
let numbers: number[] = [1, 2, 3];
2. How do you declare an array with multiple types of elements?
Answer: You can achieve this using a union type. A union type allows a variable to hold values of different types.
Example:
let mixedArray: (string | number)[] = ["hello", 42, "world", 100];
3. What are generics in TypeScript arrays, and how are they used?
Answer: Generics in TypeScript allow you to define components with placeholders for types that will be provided later. The most common use case for generics is with arrays.
Example:
let genericArray: Array<number> = [1, 2, 3];
let anotherGenericArray: Array<string> = ["a", "b", "c"];
4. Can TypeScript arrays enforce a fixed length?
Answer: No, TypeScript arrays themselves don’t enforce a fixed length. However, you can use tuples, which do specify the number and types of elements an array must contain.
5. What are tuples in TypeScript?
Answer: Tuples are fixed-length arrays where each element can have a different type specified. They are useful for ensuring a specific order and type within arrays.
Example:
let person: [string, number] = ["John Doe", 28];
6. Is it possible to add elements to a tuple after its declaration? If so, what are the restrictions?
Answer: Yes, it is possible to add elements to a tuple after declaration. However, added elements must be of the types already defined in the tuple. After declaration, additional elements can be pushed only if they match any of the existing element types in the tuple, otherwise, TypeScript will throw an error.
Example:
let person: [string, number] = ["John Doe", 28];
person.push("Male"); // Works because "Male" has a type 'any'
// However, if strict mode is enabled, you need to push type string|number
7. How do you handle optional elements in tuples?
Answer:
You can make elements of a tuple optional by using a question mark (?
) after the element type.
Example:
let user: [string, number?, string?] = ["John"];
user.push(28);
user.push("Engineer");
8. Can TypeScript tuples be used for deconstruction assignment?
Answer: Absolutely, tuples can be deconstructed into separate variables. This feature simplifies assignments from tuple elements.
Example:
let person: [string, number, string] = ["John Doe", 28, "Engineer"];
let [name, age, profession] = person;
console.log(name); // John Doe
console.log(age); // 28
console.log(profession);// Engineer
9. What are read-only tuples, and why would you use them?
Answer:
Read-only tuples are like regular tuples, but their elements cannot be modified after initialization. You create a read-only tuple using the readonly
keyword.
Read-only tuples are beneficial when ensuring data integrity and preventing unintended modifications, especially when passing arrays around as function arguments.
Example:
let readOnlyTuple: readonly [string, number] = ["Jane Doe", 25];
// Error: Cannot assign to '0' because it is a read-only property.
//readOnlyTuple[0] = "Doe Jane";
10. How do you handle rest elements in TypeScript tuples?
Answer: Rest elements allow you to capture any number of additional elements in a tuple. This is useful for creating flexible tuple types where the first elements have known types and the rest can vary.
Example:
Login to post a comment.