Infer last element of tuple type in TypeScript
29 Apr 2021
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]
:
Since TypeScript 4.2 we can use rest elements not only at the very last position of a tuple type:
With Type inference in conditional types we can skip all elements but the last one:
Done ✅
Please find the solution with test cases in Playground
Have a wonderful evening 🌆
typescript