Before TypeScript 3, tuples had to have a fixed amount of elements. TypeScript 3 gives us a little more flexibility with rest elements. rest elements are similar to rest parameters, described in the last section, but they work with tuple element types. A rest element allows us to define an open-ended tuple.
Time to go through an example:
- In the TypeScript playground, let's create a tuple with the first element being a string and subsequent elements being numbers:
type Scores = [string, ...number[]];
- We should be able to use this structure to store someone's name with an infinite amount of scores. Let's give this a go for Billy and three scores:
const billyScores: Scores = ["Billy", 60, 70, 75];
- Let's move on to try Sally and four scores:
const sallyScores: Scores = ["Sally", 60, 70, 75, 70];
Both these variables compile fine, as we would expect, because we have defined the numbers as open-ended.