How could I tell typescript that props come from react clone element?

Viewed 81

I had a gather component wrapped all my child. I assume this gather must pass "props: {index}" to every child.

Gather.tsx

const Gather: React.FC = ({
  children
}) => {
  return {
    Children.map(children, (child, index) => {
      return React.cloneElement(child as ReactElement, {
        page: index + 1
      });
    })
  }
}

GatherChild.tsx

const GatherChild = ({ page }) => {
  return <div>{ page }</div>
}

App.tsx

const App = () => {
  return <Gather>
    <GatherChild />
    <GatherChild />
    <GatherChild />
  </Gather>
}

How could I tell typescript I will definitely give it the props?

1 Answers

its an old question but maybe someone else need the answer.

We need to rearrange the code a little:

interface ProvidesHeightInjectedProps {
    page: boolean;
}

interface Props {
  children(props: ProvidesHeightInjectedProps): React.ReactElement<any>
}

const Gather: FunctionComponent<Props > = ({
  children
}) => {
  return children({ page: index + 1})
}
const App = () => {
  return (
     <Gather>
      {({ page }) => (
          <GatherChild page={page} />
          <GatherChild page={page} />
          <GatherChild page={page} />
      )}
     </Gather>
  )
}
Related