DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Typescript Series - First and Last of Array Type
Sarmun Bustillo
Sarmun Bustillo

Posted on

Typescript Series - First and Last of Array Type

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[0];
const last = arr[arr.length - 1]

// or

const [first, ...rest] = arr;
const [...rest, last] = arr;

Enter fullscreen mode Exit fullscreen mode

To create our Types we will use the array destructuring approach

The Types

type First<Type extends unknown[]> = Type extends [infer R, ...unknown[]] ? R : never

type Last<Type extends unknown[]> = Type extends [...unknown[], infer R] ? R : never
Enter fullscreen mode Exit fullscreen mode

For both of our desired types we are following the same principle, so let's break one down.

Understanding the infer keyword

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).

Thank you!

you can find me here My Twitter

Top comments (2)

Collapse
tylim88 profile image
Acid Coder • Edited on

there is an easier way to get the first type

type a = [1,2,3,4]

type b = a['0'] // 1
type c = a[0] // 1
Enter fullscreen mode Exit fullscreen mode

playground

does not work on empty tuple though

Collapse
sarmunbustillo profile image
Sarmun Bustillo Author

That's exactly right! that is the other approach

🌚 Life is too short to browse without dark mode