Explain it simply
Explain it simply
Think of an array type as the label on a box. A box labelled "eggs only" can hold any number of eggs, but not an apple. number[] works the same way: it can hold as many numbers as you like, and TypeScript stops you from putting a string in.
The label pays off when you take things out, too. TypeScript knows that numbers[0], or each value inside numbers.map(...), is a number, so you get autocomplete and safe access to number methods.
Problem → Why → Solution
The problem: one string sneaks in
When scores are collected from a form, an input field often hands back its value as a string. In plain JavaScript, summing [90, 85, "77"] does not give 252 but the string "17577", because 175 + "77" is string concatenation. No error is raised, and a wrong average ends up in the report.
// Plain JavaScript: nothing says what the array may contain
const scores = [90, 85, "77"]; // "77" came from a text input
let total = 0;
for (const score of scores) {
total += score; // 90 -> 175 -> "17577"
}
console.log(total / scores.length); // 5859, not 84Why does this happen?
JavaScript arrays put no limit on element types, and + concatenates instead of adding when one side is a string. Declaring const scores: number[] makes the line with "77" a compile error. Even without the annotation, TypeScript infers (string | number)[] and rejects total += score.
Core concept: one element type, any length
There are two ways to write an array type and they mean the same thing: number[] and Array<number>. number[] is shorter and more common in everyday code; Array<T> is the generic form (generics come in a later lesson). An array type describes one element type and says nothing about length: a number[] may hold zero elements or thousands. When each position needs its own type, such as [id, name], you need a tuple, covered in the next lesson.
Without an annotation, TypeScript infers the type from the literal's elements. [1, 2, 3] is number[], while [1, "two", 3] is (string | number)[]: every element may be a string or a number. Mind the parentheses: (string | number)[] is one array that may mix both, whereas string[] | number[] is either an all-string array or an all-number array. For an empty array, const items = []; leaves TypeScript guessing from what you add later, so it is clearer to write const items: string[] = []; up front.
Array methods carry types through. numbers.map(n => n.toFixed(1)) returns string[], and filter returns number[] again. find may not find anything, so it returns number | undefined and makes you check before use. Index access is the exception: numbers[10] is typed number, yet with five elements it is undefined at runtime. The tsconfig option noUncheckedIndexedAccess tightens this; with it on, numbers[i] has type number | undefined.
The element type can be any type at all. An array of objects is Product[] or { name: string; price: number }[], and a grid of arrays inside an array is number[][]: grid[0] is a number[] and grid[0][1] is a number. However complex the element, the rule is the same: put [] after the element type.
- The label names the element type
- Every push is checked against it
- Reading gives back the element type
- find / index may come back empty
An array type says what each element is, never how many elements there are.
General pattern
const list: ElementType[] = [item1, item2];
const same: Array<ElementType> = [item1, item2];
const mixed: (TypeA | TypeB)[] = [a, b];
const empty: ElementType[] = [];
function read(values: readonly ElementType[]): Result { ... }The first two lines mean the same thing. Wrap a union element type in parentheses and always type an empty array. readonly ElementType[] stops the function from modifying the array.
Example: two ways to declare an array
This example declares a number array in the T[] form and a string array in the Array<T> form. Uncomment the push("hello") line yourself to see the exact error TypeScript reports. Then try reading numbers[20] and hover over it in your editor: the type still says number, which is the index-access gap described above.
let numbers: number[] = [1, 2, 3, 4, 5];
// numbers.push("hello"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
let strings: Array<string> = ["a", "b", "c"];
console.log(numbers[2]);Code breakdown
- Line 1
let numbers: number[] = [1, 2, 3, 4, 5];numbers may hold only numbers. The literal contains only numbers, so number[] would be inferred even without the annotation.
- Line 2
// numbers.push("hello");Uncommented, this gives "Argument of type 'string' is not assignable to parameter of type 'number'". push()'s parameter type comes from the element type.
- Line 4
let strings: Array<string> = ["a", "b", "c"];Array<string> is exactly string[], written in generic form.
- Line 6
console.log(numbers[2]);Indexes start at 0, so numbers[2] is the third element, 3. It is typed number, but numbers[20] would also be typed number while its value is undefined.
3How array methods carry types
You never write the callback's parameter type: TypeScript knows p is a number from prices. map builds a new array type from the callback's return type, and find's result can only be used after checking that it is not undefined.
const prices = [1200, 450, 3000]; // number[]
const labels = prices.map((p) => `${p} MMK`); // string[]
const cheap = prices.filter((p) => p < 1000); // number[]
const big = prices.find((p) => p > 2000); // number | undefined
console.log(labels.join(", "));
console.log(cheap);
if (big !== undefined) console.log(big.toFixed(1));
const mixed = [1, "two", 3]; // (string | number)[]
console.log(mixed.length);readonly arrays and the sort() trap
readonly number[] has no mutating methods: no push, pop, sort or splice. If a function only reads the caller's array, make its parameter readonly. This example sorts a copy ([...values]), so the original is untouched. The last line shows that sort() without a compare function orders numbers as strings, which puts 100 before 72.
function sorted(values: readonly number[]): number[] {
// values.sort() would be an error: sort does not exist on readonly number[]
return [...values].sort((a, b) => a - b);
}
const scores: readonly number[] = [72, 9, 100];
console.log(sorted(scores));
console.log(scores);
console.log([72, 9, 100].sort());In real projects
Where this shows up in real projects
Most data in real apps is a list: orders returned by an API, items in a shopping cart, rows in a table, options in a dropdown. With a type such as Order[], you get autocomplete for order.total and order.status inside orders.map(order => ...), and the day a field is renamed, the compiler lists every loop over that list.
In React, pushing into a state array directly causes a classic bug where the component does not re-render, so many teams use readonly arrays and spreads ([...items, newItem]) instead. In search results and lookups, TypeScript's reminder that find() can return undefined makes it hard to forget the "nothing found" state in the UI. Just as with objects, an API that promises Order[] may still send something else at runtime, so validate the list once where it enters the app.
Common mistakes
Common mistakes
1. Assuming arr[i] always exists
items[0].name compiles, but on an empty array it crashes at runtime with "Cannot read properties of undefined". Check length, use items[0]?.name, or turn on noUncheckedIndexedAccess so the compiler makes you check.
2. Silencing find() with !
Adding ! as in users.find(u => u.id === id)!.name removes the error but not the crash when the id is missing. Store the result, check if (!user), and really handle the "not found" case.
3. Sorting numbers with a bare sort()
[72, 9, 100].sort() returns [100, 72, 9] because the default sort compares elements as strings. TypeScript cannot catch this since the types are fine. Always pass sort((a, b) => a - b), and remember that sort() also mutates the original array.
Best practices
Best practices
- Pick one style, T[] or Array<T>, for the whole team and use it consistently.
- Give array parameters a readonly T[] type when the function only reads them, so the caller's data cannot change by accident.
- Consider turning on noUncheckedIndexedAccess in new projects so every indexed read must be checked.
Mini challenge
Mini challenge: temperature stats
Write three statistics functions that take a week of temperatures as a read-only array.
- average(values) returns 0 for an empty array
- above(values, limit) returns the values greater than limit as number[]
- firstBelowZero(values) returns number | undefined, and the caller handles undefined
- Every parameter is readonly number[]; the original array must not change
function average(values: readonly number[]): number {
// TODO: guard the empty array, then sum and divide
}
function above(values: readonly number[], limit: number): number[] {
// TODO
}
function firstBelowZero(values: readonly number[]): number | undefined {
// TODO
}
const temps: readonly number[] = [31, 34, 29, 36, 33];
// TODO: print the average (1 decimal), values above 32, and the first below zeroExpected: It prints: Average: 32.6 Above 32: 34, 36, 33 Below zero: none Empty average: 0
Show hint
Sum with reduce((sum, v) => sum + v, 0). firstBelowZero(temps) ?? "none" replaces undefined with a fallback text.
Show solution
function average(values: readonly number[]): number {
if (values.length === 0) return 0;
const total = values.reduce((sum, v) => sum + v, 0);
return total / values.length;
}
function above(values: readonly number[], limit: number): number[] {
return values.filter((v) => v > limit);
}
function firstBelowZero(values: readonly number[]): number | undefined {
return values.find((v) => v < 0);
}
const temps: readonly number[] = [31, 34, 29, 36, 33];
console.log(`Average: ${average(temps).toFixed(1)}`);
console.log(`Above 32: ${above(temps, 32).join(", ")}`);
console.log(`Below zero: ${firstBelowZero(temps) ?? "none"}`);
console.log(`Empty average: ${average([])}`);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- number[] and Array<number> mean the same: one element type, no fixed length.
- A mixed literal becomes (string | number)[]; always annotate an empty array.
- map and filter carry types through, find returns T | undefined, and arr[i] is typed T but may be undefined.
- Use readonly T[] for parameters you only read, and sort numbers with sort((a, b) => a - b).
TypeScript Handbook — TypeScript