reactjstypescripttypescript-generics

How to pass a generic type in a React component props


I have a component that takes an array of options which is defined as follows:

interface Props {
  options: {
    label: string;
    value: string;
  }[]
}
function MyComponent(props: Props) {...}

And implemented like this:

<MyComponent
  options={[
    { label: "Right Hand", value: "RIGHT" },
    { label: "Left Hand", value: "LEFT" }
  ]}
/>

In this example I give options to select a dominant hand and I've defined a type for that like this:

type DominantHand = "RIGHT" | "LEFT"

Is it possible to make MyComponent flexible to specify the type of options?

I've tried to accomplish this like the following but obviously the syntax isn't correct here:

type DominantHand = "RIGHT" | "LEFT"
type Gender = "MALE" | "FEMALE"

interface Props {
  options<T>: { // this syntax is wrong
    label: string;
    value: T;
  }[]
}
function MyComponent(props: Props) {...}

...

<MyComponent
  options<DominantHand>={[ // <--- this syntax is wrong
    { label: "Right Hand", value: "RIGHT" },
    { label: "Left Hand", value: "LEFT" }
  ]}
/>
<MyComponent
  options<Gender>={[ // <--- this syntax is wrong
    { label: "Male", value: "MALE" },
    { label: "Female", value: "FEMALE" }
  ]}
/>

Is there a way to accomplish this?


Solution

  • After I have read the official typescript documentation I would suggest the following:

    function MyComponent<T>(props: {
      options: {
        label: string;
        value: T;
      }[];
    }) {
      return <div>MyComponent</div>;
    }
    
    
    type DominantHand = "RIGHT" | "LEFT";
    
    function ParentComponent() {
      return (
        <MyComponent<DominantHand>
          options={[
            { label: "Right Hand", value: "RIGHT" },
            { label: "Left Hand", value: "LEFT" },
          ]}
        />
      );
    };