Web Analytics

Arrays & Tuples

Beginner ~20 min read

Arrays and tuples let you store collections of values with type safety. Arrays hold multiple values of the same type, while tuples hold a fixed number of values with specific types in specific positions.

TypeScript Arrays vs Tuples Comparison

Array Types

TypeScript provides two syntaxes for array types:

Output
Click Run to execute your code

Array Methods

TypeScript arrays have all JavaScript array methods with full type safety:

Output
Click Run to execute your code

Readonly Arrays

Use readonly or ReadonlyArray to prevent modifications:

Output
Click Run to execute your code

Tuples

Tuples are arrays with fixed length and specific types for each position:

Output
Click Run to execute your code

Tuple Destructuring

Extract tuple values into separate variables:

Output
Click Run to execute your code

Exercise: Shopping Cart

Task: Create a shopping cart with arrays and tuples!

Output
Click Run to execute your code

Summary

  • Arrays: type[] or Array<type>
  • Readonly arrays prevent modifications
  • Tuples have fixed length and specific types per position
  • Destructuring extracts values from tuples

What's Next?

Next, we'll learn about Enums - a way to define named constants!