Intro to Generics 9 exercises

Replace the unknown Type with a Generic

The solution here is to use a generic type on the returnWhatIPassIn function.

To do this, add a <T> before the parentheses, then the t that is returned will be the same type as T:

const returnWhatIPassIn = <T>(t: T) => {
return t;

To make this more clear we can repl

Loading solution


0:00 The solution here is to use a generic type on this function here. What you can do is you can add a T into this section of the function just before the arrow parentheses here. We can pass in T as the thing that we're passing in. Then that's going to return T. If we hover over this, we've got a bunch of Ts hanging out here.

,0:22 If we make this the param that we've passed in, what we end up with is T. Then param is T. It's returning T, too. The way you can think about this is, "Return what I pass in." We have our T here. Then we return to you. This means that if we have type one, if we say, "Return what I pass in one," then that's going to be typed as one here.

0:47 This is exactly the same thing except we're creating a type helper out of this function. When we call it with different arguments with the one here, or with the return what I pass in mat, you notice that if you hover over them, they get instantiated here, too.

1:05 You can see, "Return what I pass in." We can actually see the thing that's being passed in, param is mat. It returns mat. You notice that I don't actually have to annotate the return type here. I can annotate it like this. I can say, "T gets returned here." I don't need to because TypeScript understands that param is T.

1:24 We're returning param, so we must be returning T from the function. This means that one gets typed as one, mat gets typed as mat. This way of thinking about it is totally correct. You can think of it as a type helper. In other words, it's just making sure that the outer layer of the function, the way that...its public API is basically a type helper now. You can pass in a type and return a type from it.