Optional tuple elements

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:

  1. Let's create a type for between one and three scores:
   type Scores = [number, number?, number?];
  1. 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.

  1. 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:

  1. If we try no elements, we again get ...

Get Learn React with TypeScript 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.