Constraining and Narrowing an Identity Function
We'll start the solution by wrapping
F.Narrow like before:
The next step is to constrain the shape things coming in. To do this we'll use the
extends keyword and give it an array of objects with
0:00 Let's set this up like we had it before. We've got our TFruits here. We need to wrap this in F.Narrow, or if you're coming from the future, use this const here. We also need to constrain the things that are coming in. We can't just pass in random strings here.
0:17 What we're going to do is we're going to say extends, name string, and then age number. Then we're going to wrap this in an array to express an array of those things. Here now, we're basically using...sorry, not age number, price number. There we go. Now, even though we've got a constraint happening, this is now going to infer all of the pieces down to their literal values.
0:40 This is so cool because it means we can do things like let's say type FruitName equals typeof fruits, and then say number, for instance, and then go name. This basically takes that typeof fruits that we got there, turns it into, or rather, extracts out the type of the array, grabs an index or grabs a union type of the members of that array.
1:08 You end up with either name apple or name banana, and then we can go in and grab name, and that will grab apple or banana. You can start to see just with a really simple little bit of construction here, little identity function, we're able to get really, really nice inference that we can then extract out, for instance.
1:31 This exercise shows you that it's possible to mix together constraints with narrowing, in a really nice way.