简体   繁体   中英

React/TypeScript: Specifically type props.children to component

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

Try this ( reference )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM