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

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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.