Type Transformations Workshop (4 exercises)
solution

Use a Utility Type to Extract a Function’s Return Type

The solution here has two parts.

First we need to use the ReturnType type helper from TypeScript.

This is a utility type and it's one of many that TypeScript exposes to help you with type transformations.

Passing typeof myFunc to ReturnType will give us the return type of myFunc:

Let's break this down a bit.

Consider this line of code:

This says “take the information from the type signature of our function myFunc and assign it to the type MyFunc.”

The pattern here is a really powerful, as it allows us to extract types from runtime code instead of declaring them manually.

For our example, anything we add to to our function myFunc will then be reflected in the type. This is pretty amazing!

Now that we have the MyFunc type, we can access its return type using the ReturnType helper.

Examining ReturnType

Navigating to the definition of ReturnType, we can see that it actually does have its own type definition that is globally available without needing to be imported:

Back in our code, we can treat ReturnType like a function that returns a type. If we pass in the MyFunc type into ReturnType , we can create a new ReturnValue type:

We will be creating our own versions of these type helpers later on.

Transcript

[0:00] The solution here has two parts. First of all, we need to use the return type -- type helper from TypeScript. This is a utility type. It's part of many that TypeScript exposed to help you with these transformations. The next thing is to pass it in there, we need to pass in type of my funk.
[0:18] Let's break this down. We have, "Type my funk equals type of my funk." What this does is it takes the information that you have here and it puts it into a type. This means that we can add anything to this, so arg

: [0:33] string.

[0:34] It will then be reflected in the type. This is a really, really powerful pattern, because it means that instead of needing to declare this type, we can actually extract it from the runtime code, which is amazing. Now that we have this my funk thing, all we need to do is access the thing at the end here.

[0:53] We can do that with the return type helper. If we command click this, you can see that actually it has a type definition itself. I don't need to import this from anywhere, by the way. It's just global available. I can then say, "Type return value equals return type," and pass in my funk.

[1:14] Now, what this means is that this is like a function that returns a type, a type helper. You can create your own versions of these, which we will be doing later. What this means is, we end up with the value or the type of string inside return value.