【发布时间】:2021-08-31 12:15:38
【问题描述】:
我已经写下了这个高阶组件:
type WrappedComponentConditionallyHidden =
<P>(WrappedComponent: React.ComponentType<P>) => React.FC<P & { isHidden: boolean }>;
const hideConditional: WrappedComponentConditionallyHidden = (WrappedComponent) => {
return (props) => {
// typeof props is inferred here correctly: P & { isHidden: boolean }
// Don't want to pass down "isHidden"
const { isHidden, ...passedProps } = props;
if (props.isHidden) {
return null;
} else {
return <WrappedComponent {...passedProps} />
// Passing { ...props } works but ^^^^ this fails
}
}
}
我收到这个 Typescript 错误:
Type 'Pick<PropsWithChildren<P & { isHidden: boolean; }>, "children" | Exclude<keyof P, "isHidden">>' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'
Type 'Pick<PropsWithChildren<P & { isHidden: boolean; }>, "children" | Exclude<keyof P, "isHidden">>' is not assignable to type 'P'.
'Pick<PropsWithChildren<P & { isHidden: boolean; }>, "children" | Exclude<keyof P, "isHidden">>' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{}'.
对我来说,'Pick<PropsWithChildren<P & { isHidden: boolean; }>, "children" | Exclude<keyof P, "isHidden">> 应该等于 PropsWithChildren<P>,因此它应该可以工作。任何想法为什么它不会?
【问题讨论】:
-
听起来编译器的推断对类型感到困惑。我不知道这是否可行,但您可以尝试提供一些帮助:
const { isHidden, ...passedProps }: { isHidden: boolean, passedProps: PropsWithChildren<P> } = props;。至少你可能会得到一个更有帮助的编译器错误,告诉你为什么不能转换传播变量。
标签: reactjs typescript typescript-generics react-typescript