Intro to Generics 9 exercises

Use Multiple Generics with a Function

The solution to this challenge is to use multiple generics at once.

In this case, I'll use A and B.

Here's what returnBothOfWhatIPassIn looks like now:

const returnBothOfWhatIPassIn = <A, B>(a: A, b: B) => {
return {

With this change in place, the

Loading solution


0:00 The solution for this exercise is to basically use multiple generics at once. We can add multiple, just like we did when we were doing a type helper, by adding an A and a B here. We can name these, of course, whatever we want to. Let's say First and Second, for instance. For clarity, let's just say A and B. Then we can assign them to a and b here.

0:23 What happens is that we end up with string and number being inferred here. This is interesting. You would expect this actually to be a and 1 here. When you start using multiple generics and multiple arguments, TypeScript gets more cautious about the way that it infers this stuff.

0:39 If we want it to really infer deeply what's being passed, then we pass in a stronger constraint here. We would say A extends a string. Now it's going to give us a tighter literal sense there. Actually, if you look down here, it's only asking for a string and number, so we're already doing pretty good.

0:58 This is exactly the same, of course. We type ReturnBoth of what I pass in. Let's just say A and B here. Then we say a is A and b is B. This syntax maps on really well. You can do exactly the same type of things as you can do in a generic function as you can do in a type helper.