You can add specific types for each array index by using TypeScript tuples, for example, like so:
type tuple = ['foo'|'bar', number, boolean?]; const ex1: tuple = ['foo', 1, true]; const ex2: tuple = ['bar', 1, false]; const ex3: tuple = ['bar', 1, undefined]; const ex4: tuple = ['foo', 1]; // ...
tuple type in this example specifies that an array should contain two to three elements, with their expected types specified at corresponding indexes. This means, for example, that the following values would be invalid:
// Error: Type 'string' is not assignable to type 'boolean | undefined'. const ex5: tuple = ['foo', 1, 'test']; // Error: Type '"qux"' is not assignable to type '"foo" | "bar"'. const ex6: tuple = ['qux', 1, false]; // Error: Type '["foo"]' is not assignable to type 'tuple'. Source has 1 element(s) but target requires 2. const ex7: tuple = ['foo']; // ...
As you can see in the examples above, with tuples, you can easily restrict an array to have only a certain, specific set of types at each index.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.