beraliv

Infer last element of tuple type in TypeScript

Example of Chainable Options use
Example of Chainable Options use

Today we discuss Last of Array

We already know how to get the first element. We can use it for both arrays and tuples, but for tuples you get exact value.

To distinguish arrays and tuples, please visit Making object out of tuple

Extracting last element

For the first element, we don't need an iteration over tuples and we just use [0]:

First solution
First solution

Since TypeScript 4.2 we can use rest elements not only at the very last position of a tuple type:

Rest elements in TypeScript 4.2
Rest elements in TypeScript 4.2

With Type inference in conditional types we can skip all elements but the last one:

Solution
Solution

Done ✅

Please find the solution with test cases in Playground

Have a wonderful evening 🌆

typescript

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter