Search code examples
javascriptreactjsflowtype

How to to copy Flow type of properties from another React component?


I am creating a component that wraps another component called Button. Button is defined in library that does not export type of Button's properties.

To correctly type my component, it would be ideal to copy the type of Button's properties, add a few properties to that type (using typeof, $Diff or alike) and use it as type of my component StyledButton.

Something like:

type AddedPropsT = {
  isStyled: boolean,
}

function StyledButton(props: $GenericParam(typeof Button) & AddedPropsType) {
  return (<Button ...props className={isStyled ? "StyleClass" : ""} />)
}

Of course type util $GenericParam does not exist in Flow. The type of Button is React.ComponentType<Props> (the question is how do I get that Props type from there) and behind the scenes it is pure function stateless component.


Solution

  • You can use React.ElementConfig<typeof Component> utility type to get Button's props type:

    type AddedProps = {
      isStyled: boolean,
    }
    
    function StyledButton(props: React.ElementConfig<typeof Button> & AddedProps) {
      return (<Button {...props} className={props.isStyled ? "StyleClass" : ""} />)
    }