April 27, 2025

Understanding Arrays, Tuples, and Enums in TypeScript

TypeScript enhances JavaScript by adding static types, making it easier to catch errors early and improving code readability and maintainability. Among the various offered features, arrays, tuples, and enums are fundamental concepts that every developer should understand. In this post, we’ll dive into each of these features, explaining their purpose, how they differ, and how to use them effectively in your code.

Arrays

In JavaScript, arrays are a collection of elements that can be of any type. TypeScript builds on this by allowing you to specify the type of elements within an array, ensuring that all items stored in the array are of the same type. This can help avoid potential runtime errors and improve code quality.

Declaring Arrays

To declare an array, you can use two different syntaxes:

Using square brackets ([]):

let numbers: number[] = [1, 2, 3, 4, 5];

Using the Array generic type:

let numbers: Array<number> = [1, 2, 3, 4, 5];

Both of these notations declare an array of numbers, but the choice of syntax is a matter of preference. The key idea is that the array will only accept elements of the specified type, providing better type safety.

Array Operations

Arrays in TypeScript work similarly to those in JavaScript. You can access elements by their index, use array methods like .push(), .pop(), and .map(), but with the added benefit of type checking:

let colors: string[] = ["red", "green", "blue"];
colors.push("yellow"); // This is valid
colors.push(123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'

Tuples

While arrays are great for lists of items of the same type, sometimes you need to work with a fixed-size collection where the types of elements can differ. This is where tuples come in. A tuple allows you to define an array with elements of different types and enforce a specific length for the array.

Declaring Tuples

To declare a tuple, you define the types of the elements in the array:

let user: [string, number, boolean] = ["Alice", 30, true];

Here, user is a tuple with three elements:

Tuples are ideal for scenarios where you need to store multiple related values of different types but want to ensure that the types and order of elements are respected.

Accessing Tuple Elements

Accessing elements in a tuple is similar to working with arrays. You can use indices to retrieve values, but TypeScript will enforce the types based on the tuple declaration:

let user: [string, number, boolean] = ["Alice", 30, true];

let name = user[0]; // string
let age = user[1]; // number
let isActive = user[2]; // boolean

If you try to assign a value of the wrong type, TypeScript will give you an error:

user[1] = "thirty"; // Error: Type 'string' is not assignable to type 'number'

Enums

Enums are a powerful feature in TypeScript that allow you to define a set of named constants. They can make your code more readable and reduce errors by providing meaningful names instead of hardcoded values.

Declaring Enums

Enums can be numeric or string-based. By default, numeric enums start at 0, but you can specify the starting value or assign values explicitly.

Numeric Enums:

enum Direction {
  Up, // 0
  Down, // 1
  Left, // 2
  Right, // 3
}

let direction: Direction = Direction.Up;
console.log(direction); // Output: 0

You can also specify custom starting values:

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}

let direction: Direction = Direction.Left;
console.log(direction); // Output: 3

In this example, Direction.Up starts at 1, and the rest of the values are incremented automatically.

String Enums:

String enums allow you to assign string values to each constant, which can be useful when you need to use more descriptive values.

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

let direction: Direction = Direction.Up;
console.log(direction); // Output: "UP"

Using Enums

Enums are particularly useful when you need to define a fixed set of related values, such as directions, status codes, or user roles. They provide better readability and reduce the risk of typos.

function getDirection(direction: Direction): string {
  switch (direction) {
    case Direction.Up:
      return "Going Up";
    case Direction.Down:
      return "Going Down";
    default:
      return "Unknown direction";
  }
}

console.log(getDirection(Direction.Up)); // Output: "Going Up"

Conclusion

Arrays, tuples, and enums are foundational features in TypeScript that help improve the structure and maintainability of your code. Arrays are ideal for storing collections of items of the same type, while tuples allow you to store heterogeneous values in a fixed-size array. Enums, on the other hand, make your code more readable and maintainable by using named constants instead of raw values.