I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.
There are many ways of getting the first or last element of an array, let's explore some:
const arr = [1, 2, 3, 4, 5]; const first = arr; const last = arr[arr.length - 1] // or const [first, ...rest] = arr; const [...rest, last] = arr;
To create our Types we will use the array destructuring approach
type First<Type extends unknown> = Type extends [infer R, ...unknown] ? R : never type Last<Type extends unknown> = Type extends [...unknown, infer R] ? R : never
For both of our desired types we are following the same principle, so let's break one down.
The infer keyword can be used within a condition in a conditional type to put the inferred type into a variable. That inferred variable can then be used within the conditional branches.
First<Type extends unknown> basically, Type extends an array of unknown type, we we don't care about the type, we just want to get the first/last element.
Type extends [infer R, ...unknown] ? R : never next, we check if Type extends an array with more than one element while we infer the type from the first/last destructured element and we also get the rest. Then, if the check passes we return the first/last element, otherwise we return never (ignored by TS).
you can find me here My Twitter