Typed Collections and Fixed Structures - Textnotes

Typed Collections and Fixed Structures


Learn how to work with arrays and tuples in TypeScript. This module explains typed arrays, readonly arrays, and tuples with practical examples and real-world use cases.

1. Typed Arrays

Typed arrays allow you to define the type of elements an array can hold. This ensures consistency and prevents invalid data from being added.

Array of Numbers


let scores: number[] = [85, 90, 78];

Array of Strings


let users: string[] = ["Muni", "Ravi", "Anil"];

Generic Array Syntax


let flags: Array<boolean> = [true, false, true];

Both syntaxes are valid and commonly used in real projects.

Type Safety Example


scores.push(95);
scores.push("high");

The second push causes a compile-time error because the array accepts only numbers.

2. Readonly Arrays

Readonly arrays prevent modification of array elements after initialization. They are useful when data should not be changed accidentally.

Readonly Array Example


let roles: readonly string[] = ["Admin", "User", "Guest"];

The following operations are not allowed:


roles.push("Manager");
roles[0] = "Super Admin";

ReadonlyArray Type


let permissions: ReadonlyArray<number> = [1, 2, 3];

Readonly arrays are commonly used for configuration values and constants.

3. Tuples and Use Cases

Tuples allow you to define an array with a fixed number of elements, where each element has a specific type.

Basic Tuple Example


let userInfo: [number, string] = [101, "Muni"];

The order and type of values must match the tuple definition.

Accessing Tuple Values


let userId = userInfo[0];
let userName = userInfo[1];

Tuple with Optional Elements


let employee: [number, string, boolean?];
employee = [201, "Ravi", true];

Real-World Use Cases for Tuples

Tuples are commonly used for:

  1. Returning multiple values from a function
  2. Representing fixed-structure data such as database records
  3. Working with key-value pairs

Example Function Returning a Tuple


function getUser(): [number, string] {
return [1, "Muni"];
}

Conclusion

Arrays and tuples are essential data structures in TypeScript. Typed arrays ensure consistency, readonly arrays protect data integrity, and tuples provide a structured way to handle fixed-length data. Understanding these concepts helps build safer and more predictable applications.