What's new
NoobsPlanet

Join our community today and enjoy an ad-free experience. Ask questions or learn about anything related to technology!

React Using Union Types in Props

Nikesh

Administrator
Staff member
Union types allow a prop to accept multiple types or specific string values.
Let’s look at both use cases.

Example 1: A prop that can be string OR number

JavaScript:
interface MyLabelProps {
  label: string | number;
}

function MyLabel({ label }: MyLabelProps) {
  return <p>{label}</p>;
}

export default function MyApp() {
  return (
    <div>
      <MyLabel label="Username" />
      <MyLabel label={42} />
    </div>
  );
}
In this case:
- The `label` prop can accept either a `string` or a `number`
- TypeScript allows both


Example 2: Restricting to specific strings (literal union)

JavaScript:
type ButtonVariant = "primary" | "secondary" | "danger";

interface MyButtonProps {
  title: string;
  variant: ButtonVariant;
}

function MyButton({ title, variant }: MyButtonProps) {
  return <button className={`btn-${variant}`}>{title}</button>;
}

export default function MyApp() {
  return (
    <div>
      <MyButton title="Save" variant="primary" />
      <MyButton title="Cancel" variant="secondary" />
    </div>
  );
}
Here:
- `variant` can only be one of the three string values: `"primary"`, `"secondary"`, or `"danger"`
- If you try to pass anything else, TypeScript will give an error
- This is super helpful when building design systems (e.g. Tailwind, Bootstrap, etc.)


🧠 Final Tip

Union types make your components flexible yet safe.
Whether you allow multiple types (like string or number) or limit to specific strings, it all helps avoid bugs and improves autocompletion in your editor.

Want to dive into enums or conditional props next? Let me know! 🚀
 
Top