Quick TS Tips: How to extract a type from an array

diballesteros

Diego (Relatable Code)

Posted on November 21, 2021

Quick TS Tips: How to extract a type from an array

Recently I had to work with some automatically generated types whilst using GraphQL. This is a very extremely useful feature! However, it can be a little cumbersome to specifically reach different custom nested types from the requests without it being too verbose.

But, being a little creative with some native Typescript functions we can find a way to handle this exact use case!

The example

First type

Let’s take for example this generated type (For the sake of the example, this will be a fairly simple type with a nested subtype):

If we wanted to extract the type of the array without it getting too verbose we could use some conditional typing from Typescript.

Extraction Type

Extraction Type

The following type allows us to extract it:

It can be a little confusing at first glance but let’s break down every portion. First, we have our ArrayElement which is a generic receiving the array itself as T.

Here the infer keyword from typescript (which must be used with extends) to declaratively introduce a new generic type U based on the given array.

Now let’s assume that the TStuff type is an array and we want to extract a singular TStuff. We could then supply the type of TStuff[] to ArrayElement



type TNestedStuff = ArrayElement<TStuff[]>;

Enter fullscreen mode Exit fullscreen mode




The result

Looking at the result of the extracted type we can now use it however we wish or even assign it as its own type to make it less verbose!

Extracted Type

Here is the code sandbox to play around with the type and the Typescript documentation :

Documentation - Conditional Types

https://codesandbox.io/s/array-type-extraction-1eohh

If you have any other way to extract a type from an array let me know in the comments below!

Originally published at https://relatablecode.com on November 21, 2021.

💖 💪 🙅 🚩
diballesteros
Diego (Relatable Code)

Posted on November 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related