The Utils Folder 10 exercises

Understanding Assertion Functions in TypeScript

In this exercise, we're going to focus on assertion functions in TypeScript.

We start with an interface User, which has properties id and name. Then we have an interface AdminUser, which extends User, inheriting all its properties and adding a roles string array property:


Loading exercise


00:00 In this exercise, we're going to look at assertion functions in TypeScript. We have here an interface user, which has an ID and name. And then we have an admin user, which extends user, so it has all the properties of user, then also adds roles string array to this.

00:16 We basically have a function inside here called assertIsAdminUser that we are using in a bunch of different places throughout our imaginary application. And inside here, we have, you can basically pass in a user, which might be a user or an admin user. And then it checks, if there's no roles in user, then it throws an error. The idea of this function is that

00:35 if the user is not an admin user, we get an error here, meaning that after it's called, we should be able to access properties that are only on the admin user, for instance, roles, but it's not working that way. Inside our handleRequest function, which we can imagine kind of handles like an admin-based request,

00:53 we have a user, which is a user or admin user. We're expecting that before assertIsAdminUser is called, we're expecting type of user to be user or admin user, which is correct. But after it's called, we're expecting it to be narrowed down into just admin user. And that's not happening right now.

01:10 In this position, user is user or admin user. Okay, not great. So we need to basically say, assertIsAdminUser, we need to add a type annotation to this to make sure that when this is called, it asserts that user is an admin user. This syntax is similar to a type predicate,

01:30 but it's a little bit different, and I'll add a link below. Good luck.