How to Allow Arbitrary Number of Elements in a TypeScript Tuple?

Create tuple types of variable length using the spread operator

If you have a set of known types at the beginning of a tuple, and you wish to allow an arbitrary number of array elements at the end that are of a particular type, then you can use the spread operator, for example, like so:

type tuple = [string, number, string, ...number[]];

This would allow zero or more array elements of type number at the end (after the first three elements, that are of a particular type, have been specified):

const ex1: tuple = ['foo', 1, 'bar'];
const ex2: tuple = ['foo', 1, 'bar', 1];
const ex3: tuple = ['foo', 1, 'bar', 1, 2, 3];
// ...

This is useful when you want to create open-ended tuples that may have zero or more elements of the same type at the end.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.