假设我们有一个Foo
渲染props.children
组件和另一个组件Bar
。两个module都导出一个 props 接口。
有没有办法强制 thatFoo
的孩子只能是类型Bar
?
理想情况下,我们可以在构建时使用 TypeScript 实现这一点。
例子:
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>
);
};
注意:我们没有使用 PropTypes