How to make Arrays that can only be read, TypeScript?
How to make Arrays that can only be read, TypeScript?
In TypeScript, to create arrays that can only be read and not modified, you can use the readonly
modifier or the ReadonlyArray<T>
utility type. Here are the methods to achieve this:
Using the readonly
Modifier with Standard Array Type: You can prepend the readonly
keyword before the array type declaration. This approach prevents the modification of the array, such as adding, removing, or altering the elements in the array.
const numbers: readonly number[] = [1, 2, 3, 4, 5];
In this example, numbers
is an array of numbers that cannot be modified after its declaration.
Using the ReadonlyArray<T>
Utility Type: Another way to create a read-only array is by using the ReadonlyArray<T>
utility type, where T
represents the type of elements in the array. This utility type ensures that the array is immutable, meaning its elements cannot be changed once the array is created.
const numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];
This example also creates an immutable array of numbers, similar to the first method but using the ReadonlyArray<T>
utility type.
Both methods ensure that the array cannot be modified after its initialization, making it effectively read-only. Attempting to modify the array, such as by using methods like push
, pop
, or directly altering its elements, will result in a TypeScript compilation error.
It's important to note that while these methods prevent the modification of the array itself, they do not make the objects within the array immutable. If the a...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào