Search code examples
typescripttypeerrortypescript-typingstypescript-genericsreact-typescript

Not able to access generic type in a component


I'm new to typescript. I am not able to figure out why I am not able to access this generic type in my component?

type frameworkType = {
  value: string;
  label: string;
};

This is how I am using my component:

<FancyMultiSelect<frameworkType> values={FRAMEWORKS} className="w-[300px]" onChange={onChange} />

Glimpse of my FanceMultiSelect Component:

export const FancyMultiSelect = <T,>({ values, className, onChange }: IFancySelectProps<T>) => {
  const [selected, setSelected] = useState<T[]>([]);
  const handleUnselect = (option: T) => {
    setSelected((prev) => prev.filter((s) => s.value !== option.value));
  };

 {selected.map((option) => {
            return (
              <Badge key={option.value} variant="secondary">
                {option.label}
            )
         }
     }

It just throws error like: Property 'value' & 'label' does not exist on type 'T'.ts(2339)

Help me out!

I tried creating my own type in FancyMultiSelect component. But that doesn't make any sense? Or is it the only possible way out?


Solution

  • You can explicitly constrain the generic type so that it always has certain properties. In this case, you could replace <T> with:

    <T extends frameworkType>