Extract the last element type from TypeScript arrays and tuples. Master conditional types with `infer` in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a generic Last<T> that extracts the type of the last element from an array.
Implement a generic Last<T> that takes an Array T and returns its last element.
For example
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type tail1 = Last<arr1> // expected to be 'c'
type tail2 = Last<arr2> // expected to be 1Change the following code to make the test cases pass (no type check errors).
type Last<T extends unknown[]> = T extends [...infer _Rest, infer Last]
? Last
: neverHow it works:
T to be an array with extends unknown[]T extends [...infer _Rest, infer Last] matches the array type and captures the last element's type? Last returns the last element's type if the array is not emptynever if the array is emptyThis challenge helps you understand array type operations and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount