Ever get stuck writing out long unions for component props based on an object? There's a cleaner way!
This post explores using keyof
and typeof
to automatically generate type unions from object keys for your React components.
The Problem:
Let's say you have a button component with different variants based on classNames:
const classNamesMap = {
primary: "bg-blue-500 text-white",
secondary: "bg-gray-200 text-black",
success: "bg-green-500 text-white",
};
// This approach is tedious and error-prone
type ButtonProps = {
variant: "primary" | "secondary" | "success";
};
The Solution: Leverage keyof
and typeof
!
Here's how to achieve the same functionality with cleaner code:
// Get the type of classNamesMap
type ClassNamesMapType = typeof classNamesMap;
// Use keyof to create a union type from the object's keys
type ButtonProps = {
variant: keyof ClassNamesMapType; // variant: "primary" | "secondary" | "success"
};
With typeof you will be able to get the type of your object, and with keyof you will be able to create union types based on the keys of your object.
Benefits:
- Reduced Code: No more manually typing out unions!
- Improved Type Safety: TypeScript automatically enforces valid variants.
-
Maintainability: Changes to
classNamesMap
are reflected inButtonProps
.
Bonus:
- Use this approach for any component prop based on an object of key-value pairs.
Spread the Knowledge!
Share this post with your fellow developers and elevate your React component typing game!
Top comments (0)