Function Overloads 8 exercises
Problem

Use Function Overloads to Infer Initial Data

This exercise is based off a real PR I made to TanStack Query.

We have a useData function, which is analogous to something like you would see in React, but doesn't actually use anything from React.

It takes in a params object that includes a fetchData function, then returns a Promise<T>.

Loading exercise

Transcript

0:00 In this exercise, we have a useData hook thing. You can think of this being analogous to something like React, but this is just a function. It's not using anything from React.

0:11 What this does is it takes in a params object, which takes in fetchData, which is a function that returns Promise T. If you can see here, we've got a fetchData function, the promise that resolves a number. Then that number data is a getData number or undefined. We've got data and number or undefined.

0:32 There's an issue here, which is it should not return undefined if initial data is passed, because if you think about this, if you look at the flow here, then this data is going to be locked in as params.initialData. If you pass in initialData, then there's going to be no moments when numData.getData is going to return number or undefined. It's always going to return number.

0:57 Your challenge then is to fix this function in order to make that work. There are a couple of solutions to this, but I want you to prioritize the one that uses function overloads here. That's what's going to get you there. By the way, this is based on a real PR that I made to TanStack Query to add this functionality there.