Arrays
suggest changeUse T[] for mutable arrays and readonly T[] for inputs that the function should not change. readonly is a shallow, compile-time restriction: it neither freezes the array at runtime nor makes the elements deeply immutable. Array methods preserve type information and can often replace manual loops.
interface Product {
id: string;
price: number;
}
function total(products: readonly Product[]): number {
return products.reduce((sum, product) => sum + product.price, 0);
}
const products = [
{ id: "book", price: 30 },
{ id: "pen", price: 12 },
] satisfies Product[];
const book = products.find(product => product.id === "book");
console.log(total(products), book?.price);
Methods such as find can fail, so their result includes undefined. With noUncheckedIndexedAccess, indexed access such as products[0] also includes undefined unless the compiler can prove that the index exists.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents