Understanding the Arrays in Typescript

In TypeScript, arrays are used to store collections of data, and the language provides powerful type features to ensure safe handling of arrays. You can declare arrays that store elements of specific types, allowing TypeScript to catch potential type-related errors during compilation.

Declaring Arrays in TypeScript

  • Using Square Brackets [] (Preferred)

let numbers: number[] = [1, 2, 3]; 
let names: string[] = ["Alice", "Bob"];
  • Using Array<Type>
    let numbers: Array<number> = [1, 2, 3]; 
    let names: Array<string> = ["Alice", "Bob"];

      Common Array Operations

      • Access Elements
       let fruits: string[] = ["apple", "banana", "cherry"]; console.log(fruits[0]); // Output: "apple"
      • Add Elements
      let numbers: number[] = [1, 2]; numbers.push(3); // [1, 2, 3]

      Remove Elements numbers.pop(); // Removes last element, array is now [1, 2]

      Iterate Over Arrays for (let name of names) { console.log(name); }

      Array of Objects

      You can create an array of objects by specifying the object type.

      type Person = {
        name: string;
        age: number;
      };
      
      let people: Person[] = [
        { name: "Alice", age: 30 },
        { name: "Bob", age: 25 },
      ];
      

      Tuple Arrays

      TypeScript tuples define arrays with a fixed number of elements and specific types for each element.

      let person: [string, number] = ["Alice", 30];
      

      Readonly Arrays

      If you want an array to be immutable, you can use readonly.

      let readonlyArray: readonly number[] = [1, 2, 3];
      // readonlyArray.push(4);  // Error: Property 'push' does not exist on type 'readonly number[]'.
      

      Multi-dimensional Arrays

      TypeScript supports nested arrays for multi-dimensional data.

      let matrix: number[][] = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
      ];
      

      Union Types with Arrays

      Arrays can hold elements of different types using union types.

      let mixedArray: (string | number)[] = [1, "two", 3];
      

      Summary

      • TypeScript arrays provide type safety by ensuring all elements conform to specified types.
      • Arrays can be declared using Type[] or Array<Type> syntax.
      • TypeScript also supports tuples, readonly arrays, and arrays with union types for greater flexibility and control.

      Related Posts

      Leave a Reply

      Your email address will not be published. Required fields are marked *