React/TypeScript: Specifically type props.children to component

Viewed 254

Let's say we have a component Foo that renders props.children and another component Bar. Both modules export a props interface.

Is there a way to enforce that Foo's children can be only of type Bar?

Ideally we could accomplish this with TypeScript at build-time.

Example:

import { createElement, FC, ReactNode } from 'react';
import { Bar, BarProps } from '../Bar';

export interface FooProps {
  children?: ReactNode; // this works
  // children?: ReactNode<BarProps>; // nope
  // children?: Bar; // nope
}

export const Foo: FC<FooProps> = (props) => {
  return (
    <div>
      {props.children}
    </div>
  );
};

Note: we are not using PropTypes

1 Answers

Try this (reference)

export interface FooProps {
  children?: React.ReactElement<BarProps> | React.ReactElement<BarProps>[]
}
Related