Inference Basics 6 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:



Loading solution

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.