DEV Community

Cover image for The Magic of keyof and typeof in Typescript
Anjan Karmakar
Anjan Karmakar

Posted on

3

The Magic of keyof and typeof in Typescript

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";
};
Enter fullscreen mode Exit fullscreen mode

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"
};
Enter fullscreen mode Exit fullscreen mode

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 in ButtonProps.

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!

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay