Designing Your Types 11 exercises

Add Multiple Type Arguments to a Generic Type

The first thing we need to do is make PromiseFunc generic by adding type parameters to it. We do this by adding the angle brackets and choosing what to call the type parameters.

In this case, since we want it to have two parameters we call them TInput and TOutput and separate them with a com

Loading solution


00:00 Okay, so we know that we need PromiseFunc as a type to be generic here. Now, the way that we need to do that is we need to basically say PromiseFunc now takes in some type parameters. You might think, and you might have seen this syntax before if you vaguely looked at this, that you might need to put the syntax here.

00:18 So you might say we need to say T input, T output here. But this doesn't seem to be making any difference because type PromiseFunc is not generic. This actually makes the declared function generic. And so these type parameters actually get applied to the function, but we need to put them before the equal sign.

00:39 So we end up like this. We have PromiseFunc and we say T input. And now as soon as we've declared T input here, it's going to instead yell at us for a different reason. So it is a generic type now, but now it just requires one type argument instead of two. So we need T input and T output. Let's have a look at this.

00:58 OK, great. So now it stopped yelling at us here, but now the example is actually input any, promise any. We're not using T input and T output. And of course, I can call these anything. I can call these T mat is great or something, you know, like it doesn't matter. These are just like variable names.

01:15 So T input, we're going to put that here because we know that T input, anything passed into the T input type parameter, that then needs to be put as the input. So now we can see that input string is working, but it's still returning promise any. So let's take the T output and stick it in the result of the promise. And now everything's working.

01:36 So we've got input string returns promise string. And inside here, we've got input Boolean returns promise number. Beautiful. So the lesson here is that you can have multiple type parameters, call them different things, and they're all going to be required by default.