In celebration of TypeScript 4.2’s recent release and the language’s continued evolution, let’s take a look at tuple types and some advanced type manipulations we can do with them.
A Tuple (rhymes with ‘couple’, not ‘pupil’) is a simple container of data. A tuple object has a fixed size, and the type of each element is known but the types don’t need to be the same.
A basic tuple definition is:
const movie: [string, number, Date] = ["Seven", 8.6, new Date(1996, 0, 5)];
This movie tuple has exactly 3 elements and they must be string
, number
and Date
in that order. These structures can be easily destructed into their component parts:
const [title, rating, releaseDate] = movie;
The great thing here is that the types of title
, rating
and releaseDate
are correct (string
, number
and Date
). Be careful how you define it though - we can’t make use of type inference as the syntax for a tuple literal is the same as an array literal.
const movie = ["Seven", 8.6, new Date(1996, 0, 5)];
const [title, rating, releaseDate] = movie;
Above, the type of movie is (string | number | Date)[]
so the type of each destructured variable is the union string | number | Date
. Also, realise that at runtime, after the TypeScript code has been converted to JavaScript, tuples (and typed arrays) are implemented as a normal JavaScript arrays. Like all things related to TypeScript, the safety and constraints for tuples only exist at compile time.
#javascript #typescript #typescript-4