Beginner's TypeScript #6

nhannguyendevjs

Nhan Nguyen

Posted on December 23, 2023

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:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on December 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #6
programming Beginner's TypeScript #6

December 23, 2023

Helpers por que utiliza-los?
programming Helpers por que utiliza-los?

February 20, 2023