Beginner's TypeScript Section 18 exercises
Problem

Constraining Value Types

Earlier we looked at a User that had a boolean isAdmin property.

But what if we had other types of roles?

We wouldn't want to use a freeform string, because there are only a set number of roles that a User could have: admin, user, or super-admin.


interface User {
id: n

Loading exercise

Transcript

0:00 Sometimes in TypeScript, you'll want to make sure that a property is not just like any string, but is one of a select number of strings. This might be 1 for numbers, too. You might want to make sure it's either , 1, 2 3, or 4, etc.

0:14 For this one, we have a user. We've worked out that our isAdmin Boolean that we had before is not quite cutting it, because users, they can either just be a normal user, they can be an admin, or they can be a super admin. We want to make sure that this role here is either going to be one of these specific strings.

0:36 This error down here, I_SHOULD_NOT_BE_ALLOWED, should not be allowed to be parsed here. This ts-expect-error, what this does is it checks for an error on the next line. If there is an error there, then it's not going to work. If I pass a number here, for instance, then ts-expect-error is going to be happy even though there's an error hiding underneath.

0:58 It's a little useful trick that I've used just to make sure that you see that there's supposed to be an error on the next line. Workout using the docs to see if you can restrict role to be one of those three things.