Collections
const: 配列の再代入は防ぐが、要素の変更は防がない
const は変数の束縛を固定するだけで、配列の内容を不変にはしません。
SourceconstArrays.ts
Node.js 22
export function addTag(tags: string[], tag: string): void {
tags.push(tag);
}TestconstArrays.test.ts
Node.js 22
import assert from "node:assert/strict";
import test from "node:test";
import { addTag } from "../../src/array/constArrays.js";
test("const配列には要素を追加できる", () => {
const tags = ["ts"];
addTag(tags, "node");
assert.deepEqual(tags, ["ts", "node"]);
});01Assertion
このテストで確認できること
- const で配列変数を宣言する
- push により配列の中身を変更できる
不変性を表すには const だけでなく readonly 型、コピー更新、必要に応じた実行時凍結を使い分けます。
OBSERVED RESULT
expected: tags after push → ["ts", "node"]
actual: ["ts", "node"]