TypeScript Arrays
TypeScript Arrays: Typed Lists and readonly Protection
TypeScript arrays store ordered lists where every element matches a specific type. You can write string[] (most common) or the generic Array<string> syntax—both compile to the exact same type.
Once an array is typed as number[], TypeScript blocks .push("abc") at compile time and automatically types items returned by .map() and .filter().
Typing Mutable and readonly Arrays
When a function reads an array without modifying it, mark the parameter readonly string[] (or ReadonlyArray<string>) so accidental .push() or .sort() mutations trigger compiler errors.
const scores: number[] = [82, 91, 76, 95];
const tags: Array<string> = ["ts", "backend"];
function averageScore(values: readonly number[]): number {
if (values.length === 0) return 0;
const sum = values.reduce((acc, val) => acc + val, 0);
return Number((sum / values.length).toFixed(1));
}
const topScores = scores.filter((s) => s >= 90);
console.log(tags, topScores, averageScore(scores));
Mixed-Type Arrays with Unions
If an array legitimately holds both strings and numbers, write (string | number)[] instead of falling back to any[].
Common Mistakes to Avoid
- Using
items.sort()on areadonlyarray:.sort()and.reverse()mutate arrays in place; use ES2023.toSorted()or[...items].sort()on a copy first. - Assuming
items[10]is guaranteed non-undefined: By default TypeScript typesscores[10]asnumber, even when out of bounds; enable"noUncheckedIndexedAccess": trueintsconfig.jsonfornumber | undefinedsafety. - Writing
string | number[]without parentheses:string | number[]means "a string OR a number array"; wrap in parentheses(string | number)[]for a mixed array.
Frequently Asked Questions
Should I write string[] or Array<string>?
Most TypeScript style guides prefer string[] for readability, saving Array<...> for complex nested element types.
Does readonly exist at runtime in JavaScript?
No. readonly is purely a compile-time safeguard; if you need runtime immutability, use Object.freeze([...]) alongside as const.
How does as const affect an array literal?
const roles = ["admin", "user"] as const turns the array into a readonly ["admin", "user"] tuple with exact literal element types.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.