Advanced Generics 9 exercises
solution

Refactoring Functions with Unnecessary Type Arguments

The solution here is to reduce it into one generic parameter TParams that represents the entire object of params being passed in. Then in the tuple is TParams["a"] and TParams["b"]:


const returnBothOfWhatIPassIn = <
TParams extends {
a: unknown;
b: unknown;
},
>(
p

Loading solution

Transcript

0:00 The solution here is to basically reduce it into one generic parameter, where you have TParams here. That represents the entire object of params that are being passed in. Then, in the tuple here, you have TParams a and TParams b.

0:15 It's actually debatable which one is better here. This one here is maybe actually a little less cleaner. You're having to do a little bit less mapping here. Whereas this one, it's like there's a bit more constraint going on. You're having to index into it both times.

0:32 I want to put into your mind the idea that you should be on the hunt for useless generics in your projects, in your functions. Really, you don't need to use both of these. When you hover over them here, you're going to see them as string and number being locked in, which is pretty nice.

0:54 When you're in this function, what you see when you hover over is actually the entire parameters that are being passed. This is basically dealer's choice. It's up to you which one you use. Experience has taught me that you should try to reduce the number of type arguments that you possibly can.

1:14 In general, fewer, it's going to be easier to refactor. You're less likely to end up with useless ones cluttering up your functions. This is something you should be aware of whenever you're writing generic functions, is that you sometimes end up with a little bit of cruft, a little bit of crap that you need to get rid of.