Arrays and Readonly Arrays
An array type describes a list whose elements all share one type, written T[] or Array<T>. Adding readonly gives you the same list seen through a narrower type that has no mutating methods on it.
Detailed Explanation
At runtime a TypeScript array is a plain JavaScript array. Nothing is added, nothing is wrapped. The type is a claim about what lives inside the list, and that claim is erased before the code runs.
There are two spellings and they mean the same thing:
const scores: number[] = [];
const names: Array<string> = [];
T[] is shorter and reads better for simple element types. Array<T> reads better when the element type is long. Note that T[] binds tightly, so a union element type needs parentheses: (string | number)[] is a list of strings and numbers, while string | number[] is a string or a list of numbers.
The more interesting half is readonly. The type readonly string[], also spelled ReadonlyArray<string>, has length, map, filter, slice, and indexed reads. It has no push, pop, sort, splice, or index assignment. It is not a frozen array. It is the same array viewed through a smaller interface, and it costs nothing at runtime because the restriction only exists in the compiler.
That leads to the assignability rule people trip over: T[] is assignable to readonly T[], but readonly T[] is not assignable to T[]. Handing a mutable array to code that promised not to mutate is safe. The reverse is not — the callee could push into a list its caller believes is fixed. So readonly T[] is the right type for a parameter you do not intend to modify. It documents the intent and the compiler enforces it.
Arrays have one well-known hole in their soundness: they are covariant. If Dog is assignable to Animal, then Dog[] is assignable to Animal[], and the compiler allows it even though the receiver can now push a Cat into your list of dogs. TypeScript accepts this deliberately, because rejecting it would make everyday code painful. readonly T[] parameters avoid the problem entirely.
The bigger everyday hole is indexing. By default arr[0] has type T, even when the array is empty. The compiler does not track length, so every index read is assumed to succeed:
const temps: number[] = [];
temps[0].toFixed(1); // compiles, then throws at runtime
The noUncheckedIndexedAccess flag fixes this by typing every index read as T | undefined. That is honest, and it catches real crashes. It also makes loops noisier, because arr[i] inside a for loop now needs a guard or a non-null assertion even when you can see the bounds are fine. for...of and array methods such as map are unaffected, since those already hand you a real element. Many teams turn the flag on and switch index loops to for...of wherever they can.
Code Examples
1. readonly parameters, and the one-way assignability rule.
// 1. readonly parameters, and the one-way assignability rule.
function totalCents(lineItems: readonly number[]): number {
// lineItems.push(100);
// Error: Property 'push' does not exist on type 'readonly number[]'.
return lineItems.reduce((sum, cents) => sum + cents, 0);
}
const cart: number[] = [1299, 450, 899];
totalCents(cart); // 2648 — a mutable array is accepted where a readonly one is wanted
const frozenPrices: readonly number[] = [100, 200];
const editable: number[] = frozenPrices;
// Error: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.2. noUncheckedIndexedAccess makes index reads honest.
// 2. noUncheckedIndexedAccess makes index reads honest.
// tsconfig.json: { "compilerOptions": { "noUncheckedIndexedAccess": true } }
const rows: string[] = ["id,name", "1,Ada"];
const header = rows[0]; // type is string | undefined, not string
// header.split(",");
// Error: 'header' is possibly 'undefined'.
if (header !== undefined) {
header.split(","); // narrowed to string
}
for (const row of rows) {
row.split(","); // string — iteration is unaffected by the flag
}3. Array covariance is convenient and unsound.
// 3. Array covariance is convenient and unsound.
class Animal { constructor(public name: string) {} }
class Dog extends Animal { fetch(): void {} }
const dogs: Dog[] = [new Dog("Rex")];
const animals: Animal[] = dogs; // allowed: Dog[] is assignable to Animal[]
animals.push(new Animal("Whiskers")); // compiles; dogs now holds a non-Dog
dogs[1].fetch(); // TypeError: dogs[1].fetch is not a functionCommon Gotchas
An out-of-bounds read is typed as if it succeeded
by default the compiler gives `arr[99]` the type `T`, so `arr[99].trim()` passes type checking and throws at runtime. Turn on `noUncheckedIndexedAccess` if you want the type to admit that the element may not be there.
`readonly` is a compile-time view, not a frozen object
the underlying array is still mutable, and any other reference to it can change it. If you need the guarantee at runtime, call `Object.freeze` as well.
`readonly T[]` and `T[]` are not interchangeable in generics
a function that takes `T[]` will reject a `readonly T[]` argument, which is why library authors accept `readonly T[]` for inputs they only read. Widening a parameter to `readonly` is a safe change; narrowing it is a breaking one.
`sort`, `reverse`, and `splice` mutate in place and return the same array
on a `T[]` this quietly reorders the caller's data. Copy first with `[...items].sort(...)` or `items.toSorted(...)` on ES2023 targets.