给定类型
type EnumerableComponentFactory = <C, I>(config: {
Container: React.ComponentType<C>;
Item: React.ComponentType<I>;
}) => React.FC<{ items: I[] }>;
通过以下实施
const Enumerable: EnumerableComponentFactory =
({ Container, Item }) =>
({ items }) =>
(
<Container>
{items.map((props, index) => (
<Item key={index} {...props} />
))}
</Container>
);
和预期用途
const UnorderedList = Enumerable({
Container: ({ children }) => <ul>{children}</ul>,
Item: ({ title }: { title: string }) => <li>{title}</li>,
});
<UnorderedList items=[{title: "Something"}] />
我观察到以下 TypeScript 错误
Type '{ children: Element[]; }' is not assignable to type 'C'.
'C' could be instantiated with an arbitrary type which could be unrelated to '{ children: Element[]; }'.ts(2322)
这引出了我的问题:我需要设置什么类型约束来解决此错误?
我尝试按如下方式更改类型:
type EnumerableComponentFactory = <C extends { children?: Element[] }, I>(config: {
Container: ComponentType<C>;
Item: ComponentType<I>;
}) => (props: { items: I[] }) => ReturnType<FC<I>>;
但这会产生一个更加神秘的错误消息,为了简洁起见,我将省略该消息。
附:该函数本身实际上完全符合预期。只是编译器出错了。