Quick TS Tips: Extracting a return type from a function

diballesteros

Diego (Relatable Code)

Posted on December 12, 2021

Quick TS Tips: Extracting a return type from a function

Splash
Photo by Spencer Davis on Unsplash

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 have any more tips regarding Typescript leave them in the comments below!

More content at Relatable Code

Originally published at https://relatablecode.com on December 12, 2021.

💖 💪 🙅 🚩
diballesteros
Diego (Relatable Code)

Posted on December 12, 2021

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

Sign up to receive the latest update from our blog.

Related