Sub topic 1
TypeScript Arrays and Tuples
Prerequisites
Assume you know JavaScript arrays and methods such as map and filter, basic TypeScript annotations, and union types. This chapter focuses on ordinary arrays. Tuples come later.
Typing arrays with `T[]` and `Array<T>`
An array type describes the type of every element. number[] means “an array whose elements are numbers.” Array<number> means the same thing. Use whichever style matches your project.
const scores: number[] = [90, 85, 72];
const names: Array<string> = ["Ada", "Linus"];
const mixed: (string | number)[] = ["a", 1, "b", 2];
scores.push(95);
// scores.push("excellent"); // ErrorThe union type in (string | number)[] allows either a string or a number in each position.
How TypeScript infers array literal types
When you initialize an array without an annotation, TypeScript usually infers an array type from its elements.
const inferred = [1, 2, 3]; // number[]
const inferredMixed = [1, "a"]; // (string | number)[]
inferred.push(4);
// inferred.push("four"); // ErrorInference is useful when the initial values clearly describe the intended type. Add an annotation when an empty array, a public API, or a wider type needs more guidance.
Reading elements and `noUncheckedIndexedAccess`
Index access reads an element by its numeric position. Without noUncheckedIndexedAccess, TypeScript often treats scores[0] as a number, even though the array could be empty. With that compiler option enabled, the result is number | undefined, so your code must handle a missing element.
const scores: number[] = [90, 85];
const first = scores[0]; // number, or number | undefined with the option enabled
if (first !== undefined) {
console.log(first.toFixed(1));
}Typing array methods and filtering with type guards
Methods preserve useful element information. A type guard is a function whose return type, such as value is string, tells TypeScript what remains after a check.
const values: (string | null)[] = ["a", null, "b"];
const strings = values.filter(
(value): value is string => value !== null,
);
const lengths = strings.map((value) => value.length);
// lengths: number[]Exercise
What is the inferred type of const values = [1, "two"];?
Show answer
(string | number)[], because the array can contain either element type.