TypeScript Generics Workshop (7 exercises)

Approaches for Typing Object Parameters

There are multiple solutions to this challenge.

Solution 1

The first solution is to add two generic parameters and replace the unknowns inside of the object:

Loading solution


[0:00] [0: 00] There are multiple solutions to this problem, but here is the first. We first of all select two generic parameters because we've got two things being passed in.
[0:08] [0: 09] You notice we don't have to say, "OK, this params is the thing we're passing in here." We can actually go deeper into that argument and say, "This piece of it is what I want you to infer."

[0:22] [0: 22] We could do this if we want to. We could say T1, for instance. Then this has to extend a string, or a any, b any, like this, and this all seems to work. We will get onto this approach later as an alternative way of doing it.

[0:39] [0: 39] This one I wanted to show because it shows how flexible you can be with these declarations. You specify all of the things you want to infer here. Then you go deeper into the object and say, "These are the slots that I want these inferences to appear in."

[0:58] [0: 58] This is really great because when you hover over this, you can see what they're being inferred as. We have a string, number, and that maps onto a being a string and b being the number. If I change this to a Boolean, then this will be inferred there, too, boolean, number. That's really, really cool.

[1:16] [1: 16] This gets even nicer when you combine this with type helpers. Here we have T1, T2. These are the things that you can infer. We can actually specify Params here as an interface that lives somewhere else, that declares its own type helpers here, its own type arguments, and then it will infer the positions of a based on this.

[1:37] [1: 37] This works for types, too, and means that you can create these type helpers that span your entire application, and the generic syntax will infer all the positions of them. So cool.