⭐ Constraining Value Types ⭐
We have a User interface below:
interface User {
id: number;
firstName: string;
lastName: string;
role: string;
}
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",
}
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";
}
✍️ 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;
}
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)