Array Types
In this page:
Basic Array Syntax
You can declare an array using the type[] syntax, such as string[] for an array of strings or number[] for an array of numbers. Every value pushed into or stored in that array must match the specified type, or the compiler flags it.
Example: Basic Array Syntax
let names: string[] = ["Amit", "Priya"];
let nums: number[] = [1, 2, 3];
console.log(names, nums);
Array Methods
Typed arrays support every normal JavaScript array method, like push, pop, map, and filter, exactly as before. The difference is that TypeScript checks the values passed to those methods, so pushing a number into a string[] array is caught immediately.
Example: Array Methods
let nums: number[] = [1, 2, 3];
nums.push(4);
// nums.push("five"); // rejected: string is not a number
console.log(nums.map(n => n * 2));
Alternative Array Syntax
TypeScript also supports the generic Array<Type> syntax as an alternative to Type[], and the two mean exactly the same thing. The generic form is sometimes preferred for readability when the element type itself is already a complex generic type.
Example: Alternative Array Syntax
let names: Array<string> = ["Kabir", "Neha"];
console.log(names);
Readonly Arrays
A readonly array, written as readonly Type[], allows values to be read normally but blocks any method that would mutate the array, such as push or splice. This is useful for function parameters where you want to guarantee the caller's array isn't accidentally modified.
Example: Readonly Arrays
let ids: readonly number[] = [1, 2, 3];
// ids.push(4); // rejected: readonly arrays block mutation
console.log(ids);
Arrays of Objects
Arrays can contain objects with a defined shape, where an interface or object type describes the properties every item in the array must have. This lets TypeScript catch a typo in a property name on any single object inside a large array of them.
Example: Arrays of Objects
interface Product {
name: string;
price: number;
}
let products: Product[] = [{ name: "Pen", price: 2 }, { name: "Book", price: 8 }];
console.log(products);
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: