How to iterate through a Component's Children in Typescript React?

CookieOfFortune picture CookieOfFortune · Dec 1, 2015 · Viewed 18.5k times · Source

How do I iterate through a React component's children in Typescript tsx?

The following would be valid jsx:

public render() {
    return (
        <div>
            {React.Children.map(this.props.children, x => x.props.foo)}
        </div>
    );
}

However, in Typescript, the type of x is React.ReactElement<any> so I have no access to props. Is there some kind of casting that I need to do?

Answer

basarat picture basarat · Dec 1, 2015

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)