How to make a readonly tuple type in TypeScript?
How to make a readonly tuple type in TypeScript?
To create a readonly tuple type in TypeScript, you can use the readonly keyword directly before the tuple type declaration. This approach ensures that the elements of the tuple cannot be modified after they are initialized. Here's how you can define a readonly tuple:
const point: readonly [number, number] = [1, 2];
In this example, point is a tuple where both elements are of type number. The readonly modifier ensures that you cannot change the values of point after it is initialized. For instance, attempting to modify any element of the tuple like point = 3; would result in a TypeScript error, indicating that the assignment to a readonly property is not allowed.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.