Quick TS Tips How to extract a type from an array
• 2 min read
Introduction
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
Let’s take for example this generated type (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
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<T>
JavaScripttype TNestedStuff = ArrayElement<TStuff[]>;
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!
Here is the code sandbox to play around with the type and the Typescript documentation :
Documentation - Conditional Types
If you see any typos or errors you can edit the article directly on GitHub
Hi, I'm Diego Ballesteros 👋.
Stay on top of the tech industry and grow as a developerwith a curated selection of articles and news alongside personal advice, observations, and insight. 🚀
No spam 🙅♂️. Unsubscribe whenever.
You may also like these articles:
- 2023-06-05T00:41:29.681Z
- 2022-10-25T11:29:26.663Z
- 2022-10-17T14:44:10.229Z
- 2022-10-10T14:02:10.349Z