Relatable Code

Back

Quick TS Tips Extracting a return type from a function

2 min read

Introduction

As part of an ongoing series of tips, I’m documenting some TS Tips.

If you’re curious about how to extract a type from an array, check out this blog post!

As I mentioned in that blog post working with GraphQL generated types can be quite cumbersome at times especially if you intend to do any post-fetching manipulation to the data.

However, with some Typescript functions, we can quickly extract a type from the result of a function!

The example

Let’s take for example this simple type:

Person Type

Nothing too crazy just a simple object with a few properties.

As well as this simple function:

Transformation function

As we can see in the function we receive a simple object type and we manipulate it adding in some new properties. For the sake of this example, the manipulation isn’t too complex and you could probably just extend the original type. More information on extending here.

However, if we were to assume we don’t have the original typing declared or the manipulation is considerably more complex it would be simpler just to extract the type from the result of the function.

Extraction Type

The following utility type from Typescript lets us directly extract the type!

Return type

Now we can set an alias or just directly use the type around our application to feel a little safer when we’re manipulating the data. This is awesome!

Now if we go through the entire series of steps:

Full example

No errors when sending in myself to the transformation function and now we can use the type anywhere else in the application!

Here’s a little sandbox to play around with the typing:

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.

Envelope
Subscribe

You may also like these articles: