Typescript Foundations / Basic Types

Arrays

πŸ‘‰ An array is a collection of elements of the same type (or union of types) stored in a single variable.

πŸ‘‰ TypeScript allows you to define exactly what kind of values an array can contain!


⚑ Ways to declare arrays

1️⃣ Type + square brackets

let numbers: number[] = [1, 2, 3, 4];
let names: string[] = ["Alice", "Bob", "Charlie"];

2️⃣ Generic Array type

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

βœ… Both styles are equivalent β€” use whichever you prefer.


3️⃣ Arrays with union types

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

➑ Array contains both numbers and strings.


4️⃣ Readonly arrays

let ids: readonly number[] = [1, 2, 3];
// ids.push(4);  ❌ Error: Cannot modify readonly array

✍ Example

let fruits: string[] = ["apple", "banana", "orange"];

fruits.push("mango");  // βœ… OK
// fruits.push(42);    
// ❌ Argument of type 'number' is not assignable to parameter of type 'string'

console.log(fruits); // ['apple', 'banana', 'orange', 'mango']

πŸš€ Array of objects

interface User {
  id: number;
  name: string;
}

let users: User[] = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" }
];

πŸ’‘ Common array operations

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

nums.push(6);         // Add element
let first = nums[0];  // Access element
let len = nums.length; // Get length

nums.forEach(n => console.log(n)); // Iterate

βœ… All of these operations are type-checked!


βš™ Best practices

  • Prefer explicit types for clarity (especially for function return types).

  • Use readonly when you don’t want the array to be modified.

  • Use tuples if position matters and types differ at each position.


✨ Summary table

Array type

Example

number[]

[1, 2, 3]

Array<string>

["a", "b", "c"]

readonly string[]

["a", "b"] (cannot modify)