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.
TypeScript 3.4 introduced enhanced support for readonly types, including readonly tuples. By prefixing any tuple type with the readonly
keyword, you make the tuple immutable, meaning that its elements cannot be reassigned after their initial assignment[1][3].
Additionally, TypeScript's type system allows you to use the readonly
modifier in more complex scenarios, such as within functions or when defining ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào