reactjstypescriptreact-functional-component

Is it possible to define a specific type for React Node children (and their props)?


If I have a functional component...

const MyParent = (props:MyParentProps)=>{

 etc...
}

...is it possible in Typescript to define that all children must adhere to a specific type or interface? eg

type IChild = (props:IChildProps)=> JSX.Element;

and...

Success

<MyParent>
  <Child/> // That implements IChild
  <Child/>// That implements IChild
</MyParent>

Failure

<MyParent>
  <BadChild/> // That doesn't implement IChild
  <Child/>// That implements IChild
</MyParent>

I just can't get Typescript to understand what i'm trying to achieve.


Solution

  • No, it is not possible.

    Instead, you can check the type of a ReactElement at runtime.

    const MyChild = () => {
      return <></>;
    };
    
    type MyParentProps = {
      children: ReactElement | ReactElement[];
    };
    
    const MyParent = (props: MyParentProps) => {
      const children = (props.children instanceof Array) ? props.children : [props.children];
      for (const child of children)
        if (child.type !== MyChild)
          throw new Error("Children of MyParent must by MyChild.");
      
      return <></>;
    }
    

    But since it's in runtime, you can't check it against a type or interface.