Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading