Skip to content

Arrays and tuples are essential data structures in any programming language, and TypeScript offers features to enhance their usage with type safety and clarity.

1. Arrays:

  • Definition: Ordered collections of elements, similar to JavaScript arrays.
  • Type Annotations:
    • Specify the type of elements within the array using square brackets [] and the element type within them.
    • Example: let numbers: number[] = [1, 2, 3]; (array of numbers)

2. Tuples:

  • Definition: Fixed-length, ordered collections of elements with specific types at each position.
  • Type Annotations:
    • Use square brackets [] and specify the type of each element within them, separated by commas.
    • Example: let employee: [string, number] = ["Alice", 30]; (tuple with string at index 0 and number at index 1)

Key Differences:

FeatureArraysTuples
LengthCan be dynamically resizedFixed length
Type HomogeneityElements can have different typesEach element must have a specific type
Use CasesGeneral-purpose collectionsRepresenting data with a specific structure and order

Examples:

TypeScript

// Array of strings
let colors: string[] = ["red", "green", "blue"];

// Tuple representing a product (name, price, stock)
let product: [string, number, number] = ["Laptop", 599.99, 10];

Additional Points:

  • Accessing elements: Use the same indexing syntax as JavaScript arrays (e.g., colors[0]).
  • Iterating over elements: Use loops (e.g., for) or array methods like forEach to iterate through elements.
  • Destructuring: Extract element values into individual variables using destructuring syntax.

TypeScript offers several built-in array methods for common operations like searching, sorting, and manipulation. Exploring the official documentation for comprehensive details and examples is recommended.

In summary, understanding arrays and tuples, along with their type annotations, empowers you to create well-structured and maintainable code in TypeScript.