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

How to Create Read-Only Arrays in TypeScript?

2024年8月7日 14:00

There are typically two ways to create read-only arrays in TypeScript: using the ReadonlyArray<T> type or the readonly modifier. I'll explain both methods in detail and provide relevant examples.

Method 1: Using ReadonlyArray<T>

The ReadonlyArray<T> type ensures that an array cannot be modified after creation (i.e., cannot add, remove, or replace elements in the array). This is enforced by TypeScript's type system.

Example:

typescript
function displayNames(names: ReadonlyArray<string>) { // Can read elements of the names array names.forEach(name => console.log(name)); // The following operations will cause compilation errors // 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);

In the above example, the names array is defined as ReadonlyArray<string>, meaning we cannot modify the array's contents.

Method 2: Using readonly Modifier

Starting from TypeScript 3.4, you can use the readonly modifier in array type definitions to create read-only arrays. These arrays prevent modifications and are used similarly to ReadonlyArray<T>, but with more concise syntax.

Example:

typescript
function displayCities(cities: readonly string[]) { // Can iterate over the cities array cities.forEach(city => console.log(city)); // The following operations will cause compilation errors // 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);

In this example, cities is defined as readonly string[], ensuring the array's contents cannot be changed after creation.

Summary

Using ReadonlyArray<T> or the readonly modifier effectively creates read-only arrays, protecting them from modification. This is particularly useful in scenarios requiring data immutability, such as functional programming or handling shared data. The choice between the two methods depends on personal or team preference, as they provide identical functionality.

标签:TypeScript