In TypeScript, declaring a fixed-length array can be achieved through two primary methods:
1. Using Tuples
Tuples are a special type in TypeScript that enable you to define an array with a fixed length, where each element can be of a different type. Additionally, if you require all elements to be of the same type with a fixed length, tuples can still be used.
For example, if you want to declare an array of length 3 where all elements are numbers, you can write:
typescriptlet fixedLengthArray: [number, number, number] = [1, 2, 3];
Once defined, fixedLengthArray has a fixed length of 3 and can only hold number types.
2. Using as const Assertion
When declaring an array and fixing both its content and length, you can use as const. This not only fixes the array's length but also makes each element a literal type, resulting in the entire array being read-only.
For example:
typescriptconst fixedLengthArray = [10, 20, 30] as const;
After applying as const, fixedLengthArray is inferred to have the type readonly [10, 20, 30], meaning you cannot modify the values or the length of the array.
Example Use Case
Imagine you are developing a feature that processes an RGB color value with a well-defined structure. The color value should be an array of three elements (red, green, blue), each being a number between 0 and 255. Using tuples to define this RGB array is highly suitable:
typescripttype RGB = [number, number, number]; function setRGBColor(color: RGB) { console.log(`Setting color to RGB(${color[0]}, ${color[1]}, ${color[2]})`); } setRGBColor([255, 135, 45]); // Correct // setRGBColor([255, 135]); // Error: parameter does not meet RGB type requirements // setRGBColor([255, 135, 45, 60]); // Error: length exceeds RGB type definition
By doing this, you can ensure that the data processed always matches the expected format and length, enhancing the reliability and robustness of your code.