How to iterate through a Component's Children in Typescript React?
Using any
should generally be avoided as you're losing the type info.
Instead use React.ReactElement<P>
in the function parameter type:
React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
However, in Typescript, the type of x is React.ReactElement so I have no access to props. Is there some kind of casting that I need to do?
Yes. Also prefer the term assertion
. A quick one:
React.Children.map(this.props.children, x => (x as any).props.foo)