react-redux-typescript-guide icon indicating copy to clipboard operation
react-redux-typescript-guide copied to clipboard

Can you provide an example for type checking JSX childrens?

Open veeramarni opened this issue 6 years ago • 3 comments

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/>)
}

veeramarni avatar Aug 09 '17 21:08 veeramarni

@boostio funded this issue with $25. Visit this issue on Issuehunt

IssueHuntBot avatar Sep 15 '18 04:09 IssueHuntBot

@issuehuntfest has funded $5.00 to this issue. See it on IssueHunt

IssueHuntBot avatar Dec 03 '18 09:12 IssueHuntBot

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

mjsarfatti avatar Apr 23 '20 10:04 mjsarfatti