Home > Enterprise >  Create a type in Typescript that can be one of specific list of React components?
Create a type in Typescript that can be one of specific list of React components?

Time:11-05

I want to create an array of components, the type of which must be limited to a few specific components:

const heroProps: HeroSectionProps = { ... }
const someOthercomponentProps: SomeOtherComponentProps = { ... }

const sections: Section[] = [<Hero {...heroProps} key="sectionheroasdfg" />, 
                             <SomeOtherComponent {...someOtherComponentProps} key="asddfasfa" />
                            ]

My problem is in defining the right type for Section, here are a few things that I have tried:

type Section = React.FC<HeroSectionProps> | React.FC<SomeOtherSectionProps>

I also tried:

type Section = typeof Hero | typeof SomeOtherComponent

Neither worked.

CodePudding user response:

You just need to concatenate the classes

type Section = Hero | SomeOtherComponent

CodePudding user response:

Instead of using React.FC, use React.ReactElement:

type Section = React.ReactElement<HeroSectionProps> | React.ReactElement<SomeOtherComponentProps>;

const sections: Section[] = [
  <Hero {...heroProps} />,
  <SomeOtherComponent {...someOtherComponentProps} />,
];
  • Related