Leverage Assertion Functions for Better Inference in Classes
The assertIsLoggedIn
function is similar to a type predicate challenge we saw earlier, so we know that we're going to need to add asserts this is
.
In this case, we need to assert that this is an SDK
and that loggedInUser
is a User
:
assertIsLoggedIn(): asserts this is SDK &
Transcript
0:00 Just like our type predicate solution that we had before, we have an assertIsLoggedIn here. We know that we're probably going to need to do asserts here. Asserts that this is what? We can have SDK and loggedInUser is a user. Whoa and it works!
0:23 You can see that before the assertion, we have this.loggedInUser is going to be user or undefined. Then after the assertion, it's user. This is amazing because it actually changes the value of this inside the class where you are. You can see this and SDK and loggedInUser. So nice.
0:47 I think the preferable version of this is to do this and/or this is this. That means that the type of this just gets something appended to it because if we're in a subclass or something like that or a superclass or whatever, then we're going to be in this and loggedInUser is exactly the type that we want.
1:08 It's amazing that this works outside of classes, but it's even more amazing that it works inside of classes. Whether you're using type predicates or using this assertion style, you're going to get this amazing logical inference just like inside the methods of your classes and outside as well.
1:26 It's so cool!