乐闻世界logo
搜索文章和话题

如何在TypeScript中创建只读数组?

浏览21
8月7日 14:00

在TypeScript中创建只读数组通常有两种方法,分别是使用ReadonlyArray<T>类型或者使用readonly修饰符。下面我会详细说明这两种方法,并给出相关的例子。

方法1: 使用ReadonlyArray<T>

ReadonlyArray<T>类型提供了一种方式来确保数组在创建后不可以被修改(不可以增加、删除、替换数组中的元素)。这是通过TypeScript的类型系统来强制实现的。

例子:

typescript
function displayNames(names: ReadonlyArray<string>) { // 可以读取names数组的元素 names.forEach(name => console.log(name)); // 下面的操作将会引发编译错误 // names.push("New Name"); // Error: Property 'push' does not exist on type 'readonly string[]'. // names[0] = "Updated Name"; // Error: Index signature in type 'readonly string[]' only permits reading. } const names: ReadonlyArray<string> = ["Alice", "Bob", "Charlie"]; displayNames(names);

在上面的例子中,names数组被定义为ReadonlyArray<string>类型,这意味着我们不能修改数组的内容。

方法2: 使用readonly修饰符

从TypeScript 3.4开始,我们可以在数组类型定义中使用readonly修饰符来创建只读数组。这样的数组同样不允许修改,使用方法和ReadonlyArray<T>类似,但在语法上更加简洁。

例子:

typescript
function displayCities(cities: readonly string[]) { // 可以遍历cities数组 cities.forEach(city => console.log(city)); // 下面的操作将会引发编译错误 // cities.push("New City"); // Error: Property 'push' does not exist on type 'readonly string[]'. // cities[0] = "Updated City"; // Error: Index signature in type 'readonly string[]' only permits reading. } const cities: readonly string[] = ["New York", "London", "Tokyo"]; displayCities(cities);

在这个例子中,cities被定义为readonly string[]类型,从而确保数组一旦创建后,其内容不可改变。

总结

使用ReadonlyArray<T>readonly修饰符可以有效地创建只读数组,保护数组不被修改,这在需要确保数据不变性的场景下非常有用,如在函数编程或处理共享数据时。选择哪种方法主要取决于个人或团队的喜好,因为它们提供的功能是相同的。

标签:TypeScript