Infer last element

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

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

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

Solution

Done ✅

Please find the solution with test cases in Playground

Have a wonderful evening 🌆

typescriptmedium

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️