📚 TypeScript — Arrays: Complete Guide with Syntax, Examples & Best Practices
🧲 Introduction – What Are Arrays in TypeScript?
In TypeScript, an array is a data structure that stores multiple values of the same type in a single variable. Arrays are a fundamental concept in both JavaScript and TypeScript, but TypeScript adds a layer of type safety, ensuring that you can’t accidentally store the wrong kind of data.
🎯 In this guide, you’ll learn:
- How to declare and type arrays in TypeScript
- Different array syntaxes (
T[]andArray<T>) - Common operations and built-in methods
- Best practices and real-world usage
🧱 Declaring Arrays in TypeScript
TypeScript supports two main ways to define arrays.
✅ 1. Using Type[] Syntax:
let fruits: string[] = ["apple", "banana", "cherry"];
✅ 2. Using Array<Type> Generic Syntax:
let scores: Array<number> = [90, 85, 100];
✅ Both are valid, and the choice is mostly a matter of style or consistency with generics.
📦 Array with Union Types
If an array can hold more than one type, use union types.
let mixed: (string | number)[] = ["Alice", 30, "Bob", 42];
✅ This array accepts both string and number values.
🧪 Common Array Operations
TypeScript supports all JavaScript array operations with type checks.
🔁 Looping through arrays:
let names: string[] = ["Alice", "Bob", "Charlie"];
for (let name of names) {
console.log(name.toUpperCase()); // safe: each item is a string
}
➕ Adding values:
names.push("Dave"); // ✅ Allowed
// names.push(100); // ❌ Error: Argument of type 'number' is not assignable to type 'string'
🧩 Multidimensional Arrays
You can define arrays of arrays for tables, grids, or matrices.
let matrix: number[][] = [
[1, 2],
[3, 4],
[5, 6]
];
📌 Explanation:
number[][]means an array of arrays of numbers.- You can access individual values like
matrix[0][1]→2.
🔍 Readonly Arrays
If you want to prevent modifications, use readonly.
let readonlyFruits: readonly string[] = ["apple", "banana"];
// readonlyFruits.push("mango"); // ❌ Error
✅ Use readonly to enforce immutability and avoid side effects.
🧠 Typed Function with Array Parameters
You can pass arrays to functions and specify the expected type.
function printAll(items: string[]): void {
items.forEach((item) => console.log(item));
}
✅ Usage:
printAll(["pen", "paper", "book"]);
🧰 Built-in Array Methods with Type Safety
TypeScript provides intelligent autocomplete and safety checks when using array methods:
let numbers: number[] = [1, 2, 3];
let doubled = numbers.map((n) => n * 2); // [2, 4, 6]
let filtered = numbers.filter((n) => n > 1); // [2, 3]
let total = numbers.reduce((a, b) => a + b, 0); // 6
✅ These methods retain type information and reduce runtime errors.
⚠️ Common Errors & How to Avoid Them
| ❌ Mistake | ✅ Solution |
|---|---|
| Using different types in a typed array | Use union types or correct the values |
| Modifying readonly arrays | Use readonly only when you need immutability |
| Forgetting to define array type | Always define type when array is empty (e.g., let a: string[]) |
💡 Best Practices for TypeScript Arrays
- ✅ Always define the type explicitly for better readability
- ✅ Use
readonlyfor immutable data structures - ✅ Use generic syntax (
Array<T>) when working with complex or reusable components - ✅ Combine arrays with union types when needed
- ❌ Don’t rely on
any[]unless absolutely necessary
📌 Summary – Recap & Next Steps
Arrays in TypeScript offer a powerful and safe way to handle lists of data. With strong typing, you can prevent many common bugs and improve code clarity.
🔍 Key Takeaways:
- Use
T[]orArray<T>to define array types - Combine union types for flexible array contents
- Utilize array methods (
map,filter,reduce) safely with autocomplete - Use
readonlyarrays to enforce immutability - Avoid the use of
any[]to maintain type safety
⚙️ Real-world relevance: Arrays are used in forms, tables, state management, APIs, data filtering, charting, and more.
❓ FAQs – Arrays in TypeScript
❓ Can I store different types in a TypeScript array?
✅ Yes, by using union types. Example: (string | number)[].
❓ Which is better: T[] or Array<T>?
📌 Both are equivalent. Use Array<T> when working with generics or nested structures.
❓ Can I make an array readonly?
✅ Yes. Use readonly keyword: readonly string[].
❓ Is it necessary to type an array?
✅ Not mandatory, but highly recommended for better intellisense and error prevention.
❓ How to initialize an empty array with type?
let items: string[] = [];
Share Now :
