Intro to Generics 9 exercises
solution

Add Types to a Class

The solution here is to open up a generic slot just after the Component. In this case I'll call it TProps. This type argument lets us infer what's being passed into the constructor, so we can update the unknown props type to be TProps. We'll do the same in the constructor as well:



Loading solution

Transcript

0:00 The solution here is to open up a generic slot just here. This Type argument let us infer what's being past into the constructor. We can say TProps is here. Now when we call component, you notice that this is being inferred in the right slot.

0:17 Currently, result is still unknown because this.props is still typed as unknown. What we can do is we can say TProps is also the same type as this. The way that this chain works is it gets inferred from the constructor, so when you call it. Then the thing that it returns has these properties.

0:38 It's slightly strange to work out the flow here, but that's the flow. Constructor first. Then that gets inferred as those private properties. We can change this of course. We can say A blah, blah, blah. A is a string. Then this will be typed as A string, B number, C number.

0:54 This is really cool. These are often a really nice place to put your generic types. Because they infer just once really when you instantiate the class, it makes them quite stable. This is a pattern that you'll see often in open source libraries but also in application code too.