Advanced Hooks 8 exercises
Problem

Use Function Overloads for Better Type Inference

This exercise is more of a thought experiment.

The maybeReturnsString function takes an input and returns a string or undefined. If you pass a string to it, the function returns that string. However, if you pass something else, the function might return a string or undefined.

You can't be ce

Loading exercise

Transcript

00:00 This exercise is really a thought experiment. We have a function here called maybeReturnsAString. And what maybeReturnsAString does, if you return it, if you pass it a string, it's going to actually return that default string there. Otherwise, it might return a string or it might return undefined.

00:19 You actually just don't know. So what we want to do here is we want to say, OK, when maybeString returns a string, we've got this hello inside here. This should be typed as string, but it's not. It's typed as string or undefined. And this one here should be typed as string or undefined. So that's good.

00:35 So you are going to need to basically find some way of doing this. I would not recommend generics for this. I would instead recommend function overloads. That's all the clue I'm going to give you. You're going to need to investigate how function overloads work.

00:52 And I will also say that this is very, very similar to the useState overloads. So the useState overloads inside here. We've actually taken a look at these before, I think. And there's just two overloads here. One where you do pass an initial state and one where you don't.

01:08 So those might be interesting to take a look at in terms of copying them over. But good luck.