Beginner's TypeScript Tutorial (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: number;
  firstName: string;
  lastName: string;
  /**
   * How do we ensure that role is only one of:
   * - 'admin'
   * - 'user'
   * - 'super-admin'
   */
  role: string;
}

Consider this defaultUser:

export const defaultUser: User = {
  id: 1,
  firstName: "Matt",
  lastName: "Pocock",
  // @ts-expect-error
  role: "I_SHOULD_NOT_BE_ALLOWED",
};

It's being defined with a role that is not one of our options.

Note that the // @ts-expect-error comment tells TypeScript that we are expecting there to be an error on the next line.

If there is not an error on the next line down, there will be a red squiggle under // @ts-expect-error. If there is an error, the line is happy and there will not be any red.

In our code's current state, we see the red line because the "I_SHOULD_NOT_BE_ALLOWED" is a string as the User interface expects, so there is no error.

Challenge

Update the User interface to restrict the role property to one of the set options.

The I_SHOULD_NOT_BE_ALLOWED role should cause an error, which will remove the red squiggly line from underneath the // @ts-expect-error line.

Transcript

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.

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.

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.

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.