Câu hỏi phỏng vấn Typescript
Câu hỏi

How to make Arrays that can only be read, TypeScript?

Câu trả lời

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:

  1. 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.

    typescript Copy
    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.

  2. 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.

    typescript Copy
    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

junior

Gợi ý câu hỏi phỏng vấn

middle

How to choose between never , unknown , and any in TypeScript?

entry

List the built-in types in Typescript

expert

What is the benefit of import assertions features in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào