react-redux-typescript-guide
react-redux-typescript-guide copied to clipboard
Can you provide an example for type checking JSX childrens?
https://github.com/Microsoft/TypeScript/issues/13618
Example: We create High-level component package with strong typed how the lower components designed to be.
type Avatar: () => JSX.Element;
interface ILoginProps {
accounts: object;
setFormType: Function;
children: Avatar;
}
class Login extends React.Component<ILoginProps, ILoginState> {
public static propTypes = {
Avatar: React.PropTypes.func,
}
public render(): JSX.Element {
const { Avatar } = this.props
return (<Avatar/>)
}
@boostio funded this issue with $25. Visit this issue on Issuehunt
@issuehuntfest has funded $5.00 to this issue. See it on IssueHunt
You have to assert the child type within the component, rather than relying on the props. Something like this should work:
// your lower component
type AllowedChildComponentProps = { ... }
const AllowedChildComponent = [...];
// the high level component
type YourComponentProps = {
children?: React.ReactElement<AllowedChildComponentProps> | React.ReactElement<AllowedChildComponentProps>[]
}
const YourComponent = (props: YourComponentProps) => {
return (
{children && React.Children.map(children, child => {
if ((child as ReactElement).type === AllowedChildComponent) {
// go ahead
} else {
// throw or something
}
}
);
}
More info: https://stackoverflow.com/q/44475309/416714