Sub topic 1
Typing arrays with `T[]` and `Array<T>`
Prerequisites
This chapter assumes basic JavaScript arrays and array methods, TypeScript type annotations, and union types such as string | number. You should know how to declare variables and call methods such as map, filter, and reduce.
Two ways to write an array type
An array is an ordered collection of values. In TypeScript, T[] means “an array whose elements have type T.” The generic form Array<T> means the same thing.
const scores: number[] = [90, 85, 72];
const names: Array<string> = ["Ada", "Linus"];
scores.push(100);
names.push("Grace");
// scores.push("excellent"); // Error: string is not assignable to numberT[] is usually shorter and easier to read. Array<T> can be clearer when the element type is complex, especially when it contains unions or nested types.
| Annotation | Meaning | Example | Column |
|---|---|---|---|
| `number[]` | Array of numbers | `[10, 20, 30]` | |
| `Array<string>` | Array of strings | `["a", "b"]` | |
| `(string \ | number)[]` | Array containing strings or numbers | `["a", 1]` |
Parentheses matter with union types. Write (string | number)[] to describe one array containing either kind of value. Without the parentheses, string | number[] means either one string or an array of numbers.
Inference from array literals
TypeScript often infers an array type from its initial values. Inference is TypeScript's process of choosing a type when you do not write an annotation.
const scores = [90, 85, 72]; // number[]
const names = ["Ada", "Linus"]; // string[]
const mixed = [1, "open", 2]; // (number | string)[]
scores.push(100);
// scores.push("high"); // Error
const firstScore = scores[0]; // numberAn inferred array usually remains mutable, so TypeScript chooses a type that allows compatible future values. If an array starts with different types, its element type becomes a union of those types.
Use an explicit annotation when it documents an important rule or prevents an overly broad type.
const ids: number[] = [];
ids.push(101);
// ids.push("101"); // ErrorIndex access and array methods
An index is a numeric position in an array. The first element has index 0.
function average(values: number[]): number {
if (values.length === 0) {
return 0;
}
const total = values.reduce((sum, value) => sum + value, 0);
return total / values.length;
}
const readings = [10, 20, 30];
console.log(readings[1]); // 20
console.log(average(readings)); // 20By default, TypeScript commonly treats readings[1] as a number, even though a requested index might not exist at runtime. With the noUncheckedIndexedAccess compiler option enabled, indexed access includes undefined, so you must check the result.
const readings = [10, 20, 30];
const value = readings[10]; // number | undefined with noUncheckedIndexedAccess
if (value !== undefined) {
console.log(value.toFixed(1));
}Array methods preserve useful element types. map transforms each element, while filter keeps elements that pass a condition.
const prices: number[] = [10, 15, 20];
const withTax = prices.map((price) => price * 1.2); // number[]
const affordable = prices.filter((price) => price <= 15); // number[]A practical model
Exercise
Exercise
Write a declaration for an array of strings, then add "done" to it without using a type assertion.
Show answer
Use const statuses: string[] = []; statuses.push("done");.