The final tuple enhancement in TypeScript 3 is the ability to have optional elements. Optional elements are specified using a ? at the end of the element type.
Let's look at another example using our scores theme:
- Let's create a type for between one and three scores:
type Scores = [number, number?, number?];
- So, we should be able to create variables to hold between one and three scores:
const samScores: Scores = [55];const bobScores: Scores = [95, 75];const jayneScores: Scores = [65, 50, 70];
As expected, this compiles just fine.
- What about four elements? Let's give this a go:
const sarahScores: Scores = [95, 50, 75, 75];
We get a compilation error, as we would expect:
- If we try no elements, we again get ...