Function Overloads 8 exercises
solution

Typing Different Function Use Cases

Let's work this solution out together.

We'll start by adding a function overload to handle the case of returning 2 when we pass in 1.

Since the function implementation signature is not exposed to the outside world, we'll create a function overload that matches it:

function retur
Loading solution

Transcript

0:00 The solution here, we know it's probably going to involve a function overload. If we add in a function overload here, let's handle this case first, because that's pretty simple to write. When we get a 1, we're going to return a 2. Now these are erroring because, of course, the function implementation signature is not exposed to the outside world. We need to write something in here.

0:23 If we add this, then a is going to be unknown, b is going to be unknown, and C is going to be unknown. What we can do is we can add a generic here. We can add a t. This is just like all the other generics that we've used. We can have T extends string, whatever, whatever, whatever. Then we can do exactly the same stuff as we had before.

0:44 In this case, when t is not equal to 1, then we're going to just treat it as T and infer it. If you hover over this, then we get the inference here. You notice if we hover over this, there's no type argument being inferred here. What this means is we can use generics on different function overload signatures to map different type argument setups.

1:10 Let's say we had T1, T2 here. Imagine these were just totally ignored. This means you need to say hello, and then you get goodbye. I've got that exercise on the brain.

1:23 Now if you were to say const goodbye equals returnWhatIPassInExceptFor1, and you were to manually pass in two type arguments, let's say wow and then cool like this, then it would force you to be in that generic slot or that function overload, which is nutty.

1:47 You can have different generic signatures on different function overloads. What this means then is that a is being inferred correctly, b is being inferred correctly, and c is being inferred correctly, but this one isn't. The question is now what do we type this as.

2:03 I like unknown and unknown being here, because we could pass in anything. This isn't being constrained by anything. It really is unknown as the signature. Then you could do unknown or 2. We do need to handle the case here. We have if t equals 1, return 2.

2:32 This represents it pretty well, because we really don't know what's going to be passed in there. It doesn't matter because the function itself is so simple. That's the lesson here, is that you can add generics onto a certain function overload if you want to.