TS Arrays

Arrays in TypeScript allow you to store multiple values of the same type. They provide strong type checks to ensure you only put values of the specified type into the array.

Key Topics

Array Declaration

You can declare a TypeScript array using either the Array<T> generic type or the T[] notation.

let numbers1: number[] = [1, 2, 3];
let numbers2: Array = [4, 5, 6];

// numbers1.push("Hello"); // Error: Argument of type 'string' is not assignable to type 'number'.
console.log(numbers1);
console.log(numbers2);

Output

[1, 2, 3]

[4, 5, 6]

Type Inference

If you initialize an array with values, TypeScript will infer the type automatically, but mixed types will cause compile-time errors unless explicitly allowed.

let inferredArray = [10, 20, 30];
// inferredArray.push("hello"); // Error: Argument of type 'string' is not assignable to type 'number'.

Explanation: The array type is inferred as number[], thus only numbers are allowed.

Common Array Methods

You can use JavaScript’s built-in array methods (e.g., map, filter, reduce) with the confidence that the items are of the specified type.

const nums: number[] = [1, 2, 3, 4];

// Using map to double each value
const doubled = nums.map(num => num * 2);
console.log(doubled);

// Using filter to get only even numbers
const evens = nums.filter(num => num % 2 === 0);
console.log(evens);

Output

[2, 4, 6, 8]

[2, 4]

Key Takeaways

  • Generic or Bracket Syntax: Both number[] and Array<number> are valid array declarations.
  • Strict Types: Inserting elements of the wrong type will be caught at compile time.
  • Inference: TypeScript infers array types if you initialize them immediately.