Combining Type Predicates with Generics
In this exercise, we're going to combine some type predicates with some generics.
We have a fake-external-lib
, where you can do a go-to definition on it and it will take you to the isDivElement
and isBodyElement
functions.
These functions take in an element and then return whether the elemen
Transcript
0:00 In this exercise, we're going to combine some type predicates with some generics. We've got this fake external library where you can actually do a go to definition on it. It will basically take you to these functions here.
0:12 These functions take in an element and then returns whether the element is an HTMLDivElement or whether the element is an HTMLBodyElement. Pretty useful. What we can do with them is we're basically creating something called a create DOM node extractor.
0:29 This is called extractBodies, extractDivs. There we go. That's a bit less of a gruesome name. What this is doing is it's going, "If we have a node of a certain type, then that node should be passed to the transform function here."
0:46 We can see this inside the DOM node extractor config. Which, what's going on here is we've got T and result, which are our two generics. We're saying, "Transform this when we take in this node, and then return the result," essentially.
1:02 The thing I want you to look at is this-is-node definition because the things that we're passing to the is node, we're passing is node is div element. This currently is not transferring its knowledge down into the transform function. If we take a look at this, you can see that it's being highlighted as unknown and any here, or those are the type arguments that are being extracted.
1:27 Whereas, what we want to do is we want to say, "Is node should be a type predicate, which is returning whether something is T or not." With those hints, I think you can solve this. Remember, you're just changing this definition. It should just work. Good luck.