読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
商品の一覧のように、プログラムの中で変えない配列には、readonly を付けられます。
const categories: readonly string[] = ["bread", "pastry", "savory", "sweets"];
categories.push("drink");
Property 'push' does not exist on type 'readonly string[]'.
readonly string[] の配列には、push や sort のように、配列そのものを変えるメソッドがありません。map や filter のように、新しい配列を返すメソッドは使えます。
| メソッド | string[] | readonly string[] |
|---|---|---|
map・filter・find | 使える | 使える |
push・pop・splice | 使える | 使えない |
sort・reverse | 使える | 使えない(toSorted などは使える) |
関数の引数を readonly の配列にしておくと、「この関数は受け取った配列を変えない」ことを型で示せます。
const calcTotalQuantity = (items: readonly ReservationItem[]): number =>
items.reduce((sum, item) => sum + item.quantity, 0);
const r2: Reservation = { id: "R-0002", name: "鈴木", pickupAt: "2026-11-02 12:30", items: [{ productId: "p004", quantity: 3 }], status: "picked_up" }; と書きます。
11 / 16