DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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:

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay