我正在处理一个返回react组件的函数,该组件将其他组件作为prop并将所有其他prop传递给它。 这是我到目前为止的内容:
interface WrappedMinimum<T> {
some: T;
}
function makePropLogger<T, P extends WrappedMinimum<T>>(warn: boolean) {
type WrappedComponentType = React.ComponentClass<P, any>;
type AdditionalProps = {
Component: WrappedComponentType;
};
return React.forwardRef<any, P & AdditionalProps>((props, ref) => {
const { Component, some } = props;
(warn ? console.warn : console.log)(some);
return <Component some={some} />;
});
}
Typescript在return
的行上报告以下错误:
Type '{ some: T; }' is not assignable to type 'P'.ts(2322)
这是有道理的,因为P可能拥有更多的道具,而不仅仅是some: T
。请记住,P扩展了{ some: T }
。下一步的逻辑步骤是传递P中的所有道具。
return React.forwardRef<any, P & AdditionalProps>((props, ref) => {
const { Component, some, ...rest } = props;
(warn ? console.warn : console.log)(some);
return <Component some={some} {...rest} />;
});
我尝试使用参数传播,但是打字稿抛出了我不理解的错误消息。
Type '{ some: T; } & Pick<PropsWithChildren<P & AdditionalProps>, "children" | Exclude<keyof P, "Component" | "some">>' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Type '{ some: T; } & Pick<PropsWithChildren<P & AdditionalProps>, "children" | Exclude<keyof P, "Component" | "some">>' is not assignable to type 'P'.ts(2322)
我如何使其工作?