Classes 9 exercises
Problem

Assertion Functions and Classes

In this exercise, we have a class called SDK that when instantiated may or may not have a loggedInUser:


export class SDK {
loggedInUser?: User;
constructor(loggedInUser?: User) {
this.loggedInUser = loggedInUser;
}
// How do we type this assertion function?
assertI

Loading exercise

Transcript

0:00 In this exercise, we have a class called SDK. The SDK may have a logged in user on it. Just like this, in fact, I could refactor this so it uses public logged in user, so I don't need to do any of this stuff. It means you can pass in a logged in user optionally when you instantiate the SDK.

0:20 We have a function here called assertIsLoggedIn. You can imagine on this SDK there might be many, many, many different methods. You can create posts, create comments, all this sort of stuff. For some of them, you need to make sure that the user is logged in.

0:36 You can imagine if we don't do this, then we throw an error, maybe we throw a 401 or something or whatever we want to do. What this does is it means that your logic for asserting the user is logged in is in one place. We know that the user can be user or undefined.

0:54 This.loggedInUser, you can imagine we're probably going to use it down here. We don't like this.loggedInUser for instance, there we go. We don't want this to be user or undefined in all the places that we're going to use it. We want it to just be user.

1:11 Your job is to find a way of typing this assertion function so that inside the class itself, it understands that loggedInUser is there when we assert that the user is logged in.