How to Make Elements of a TypeScript Tuple Optional?

Find out how to make items in 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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.