TypeScript:readonly 和 const 修饰只读数组

介绍

创建一个 不可修改、不可重新赋值 的数组

const numbers: readonly number[] = [1, 2, 3];

// numbers.push(4); // ❌ 错误!没有 push 方法
// numbers[0] = 10; // ❌ 错误!不能通过索引修改
// numbers.length = 0; // ❌ 错误!不能修改 length

// ✅ 但可以读取
console.log("",numbers[0]); // 1
console.log("",numbers.length); // 3

// ✅ 可以重新赋值整个数组(如果变量不是 const)
numbers = [4, 5, 6]; // ✅ 可以

原文出处:/show_1GW21tzI5icg.html