How to Make Elements of a TypeScript Tuple Optional?

Starting with TypeScript v3, You can make the elements of a tuple optional by marking them with ?, for example, like so:

// TS3+
type tuple = [string, number?, string?];

Following are some possibilities with the tuple type in the example above:

const ex1: tuple = ['foo', 1, 'bar'];
const ex2: tuple = ['foo', 1];
const ex3: tuple = ['foo'];

You can also allow an arbitrary number of array elements of a particular type at the end of the array by using the spread operator.


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.