DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #6

Image description

Constraining Value Types

We have a User interface below:

interface User {
  id: number;
  firstName: string;
  lastName: string;
  role: string;
}
Enter fullscreen mode Exit fullscreen mode

We would not want to use a freeform string, because a User could have only a set number of roles: admin, user, or super-admin.

Consider this defaultUser:

export const defaultUser: User = {
  id: 1,
  firstName: "Uri",
  lastName: "Pilot",
  role: "I_SHOULD_NOT_BE_ALLOWED",
}
Enter fullscreen mode Exit fullscreen mode

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

We will 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.

👉 Solution:

The solution is to update role to be a Union type.

The syntax uses | to delineate the options for which values a key can be:

interface User {
  id: number;
  firstName: string;
  lastName: string;
  role: "admin" | "user" | "super-admin";
}
Enter fullscreen mode Exit fullscreen mode

✍️ About Union Types:

Anything can be added to a union type. For example, we can make a new SuperAdmin type and add it to the role:

type SuperAdmin = "super-admin"

interface User {
  // ...other stuff
  role: "admin" | "user" | SuperAdmin;
}
Enter fullscreen mode Exit fullscreen mode

Union types are everywhere within TypeScript. They give our code safety and allow us to be really sure of the types of data flowing through our app.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)