Conditional Types and Infer 10 exercises

Optionally Infer the Return Type of a Function

Here’s what the solution looks like:

type InferPropsFromServerSideFunction<T> = T extends () => Promise<{
props: infer P
? P
: never

Let’s talk through it.

First, we want T to extend a function that returns a Promise.

Inside the Promise is an object that will contain the `p

Loading solution


0:00 The solution here is to use a conditional type, which you might have expected, to basically say, "We want T to extend a function that returns a promise." Inside that promise is going to be an object where the props are going to be in that object. We're going to infer what those props are.

0:22 This means that I can grab anything from inside here. If I say type Props = Infer this, InferPropsFromServerSideFunction and parse in typeof getServerSideProps, which is the same as down here, then we we're going to end up with json title string.

0:38 If we change this, if we add another prop and say isCool, which is true, then that's going to be inferred on the props as well.

0:48 This pattern is so useful for when you have a function that maybe you don't control. Maybe this is an external library or something and you want to extract something out of it or it's something that you do control but you don't want to declare a type annotation for.

1:04 This means that you can go in there and extract exactly what's in there and then parse that out. It means that you don't need to actually write this type declaration. You can do it from what's coming from the function itself, which is a super-powerful paradigm.