TypeScript で readonly 配列に push できない
readonly 配列に push できないときは、[...arr] や Array.from で可変コピーを作れば直る。
readonly T[] や as const の配列は変更系メソッドを型に持たないためである。
公開: 更新:
npx tsc src/bad.ts(2,6): error TS2339: Property 'push' does not exist on type 'readonly number[]'.
npx tsc
2026-10-28 に node:20(TypeScript 5.9.3 / Node.js 20.20.2) で実際に打って取った出力。検証環境の詳細
要約
Property 'push' does not exist on type 'readonly number[]' のようなエラーは、readonly T[] / ReadonlyArray<T> / as const の配列が変更系メソッドを型レベルで持たないために出る。
値を変更したい場合はスプレッドや Array.from で可変コピーを作り、それを書き換えるのが基本である。
不変性を保ちたいなら新しい配列を返す関数型の書き方に切り替える。
実行例
node:20 のコンテナで TypeScript 5.9.3 を使い、readonly number[] に push を呼ぶと、tsc は TS2339 を出して終了コード 2 で終わった。
スプレッドで可変コピーを作って push すると、エラーは消えて終了コードは 0 になった。
Version 5.9.3$ npx tsc
src/bad.ts(2,6): error TS2339: Property 'push' does not exist on type 'readonly number[]'.
$ echo $?
2$ npx tsc
$ echo $?
0— 2026-10-28 時点の出力
検証環境Node.js 20.20.2 / npm 10.8.2 / Python 3.11.2 / 2026-10-28 検証(ほか 2 件)
- 検証日
- 実行環境
node:20Debian GNU/Linux 12 (bookworm)- バージョン
- Node.js 20.20.2
- npm 10.8.2
- Python 3.11.2
- Git 2.39.5
- TypeScript 5.9.3
この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。
解決策
1. スプレッドで可変コピーを作る
const nums: readonly number[] = [1, 2, 3];
const mutable = [...nums];
mutable.push(4);Array.from(nums) でも同じ結果が得られる。
元配列の不変性を保ったまま、新しい配列だけ操作できる(公式ハンドブック(新しいタブで開く))。
2. 不変にする意図が無いなら型注釈を変える
// 変更前
const xs: readonly number[] = [1, 2, 3];
xs.push(4); // ERROR
// 変更後
const xs: number[] = [1, 2, 3];
xs.push(4); // OK3. as const を外すか、入れ子だけに使う
const colors = ["red", "green", "blue"] as const;
colors.push("yellow"); // ERROR: as const でタプル化された配列
const colors2 = ["red", "green", "blue"];
colors2.push("yellow"); // OK: string[]
type Color = "red" | "green" | "blue";
const colors3: Color[] = ["red", "green", "blue"];
colors3.push("yellow"); // ERROR: "yellow" は Color ではない4. 関数 API は readonly 受け取り・呼び出し側でコピー
引数を readonly T[] で受け取ると、関数の中で誤って書き換える事故を型で防げる。
書き換えたい場合は呼び出し側で slice() してから渡す。
function append(xs: readonly number[], x: number): number[] {
return [...xs, x];
}
const a = [1, 2, 3];
const b = append(a, 4);不変性を維持しつつ「変更後の配列」を返す関数型の書き方は、Redux / Zustand / Recoil などの状態管理ともよく合う。
よくある原因
- 変数や引数の型を
readonly T[]/ReadonlyArray<T>で宣言している - リテラルに
as constを付けたため、配列がreadonly [...]タプル型になっている - ライブラリ関数が
ReadonlyArray<T>を返しており、その結果に push しようとしている Object.freeze由来で型がreadonly化されている