【发布时间】:2020-11-09 23:43:12
【问题描述】:
我创建了一个playground of the problem
这里是代码:
type PropsWithChildren<P> = P & { children?: any };
interface FC<P = {}> {
(props: PropsWithChildren<P>, context?: any): any;
}
type BaseFields = {
label: string;
};
export type ComponentPropsType<C> = C extends FC<infer P> ? P : C;
export function renderFormControlDestructured<P extends PropsWithChildren<BaseFields>>(Comp: FC<P>) {
const Wrapped: FC<P> = ({ label, ...rest }) => {
return <Comp label={label} {...rest} />;
};
return Wrapped;
}
export function renderFormControlNotDestructured<P extends PropsWithChildren<BaseFields>>(Comp: FC<P>) {
const Wrapped: FC<P> = (props) => {
return <Comp {...props} label={props.label} />;
};
return Wrapped;
}
type SelectProps<OptionType> = {
options: OptionType[];
} & BaseFields;
const Select: FC<SelectProps<unknown>> = ({options}) => {
console.log(options)
}
const FormSelect1 = renderFormControlDestructured(Select);
const FormSelect2 = renderFormControlNotDestructured(Select);
console.log(FormSelect1, FormSelect2)
我希望 typescript 从传递的组件中推断出 Props,但我收到以下错误消息
总而言之,如果我为这样的高阶组件解构我的论点
export function renderFormControlDestructured<P extends PropsWithChildren<BaseFields>>(Comp: FC<P>) {
const Wrapped: FC<P> = ({ label, ...rest }) => {
return <Comp label={label} {...rest} />;
};
return Wrapped;
}
我收到错误消息:
Type '{ label: string; } & Pick<PropsWithChildren<P>, "children" | Exclude<keyof P, "label">>' is not assignable to type 'PropsWithChildren<P>'.
Type '{ label: string; } & Pick<PropsWithChildren<P>, "children" | Exclude<keyof P, "label">>' is not assignable to type 'P'.
'{ label: string; } & Pick<PropsWithChildren<P>, "children" | Exclude<keyof P, "label">>' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'PropsWithChildren<BaseFields>'.
但如果我不重组,我不会得到错误
export function renderFormControlNotDestructured<P extends PropsWithChildren<BaseFields>>(Comp: FC<P>) {
const Wrapped: FC<P> = (props) => {
return <Comp {...props} label={props.label} />;
};
return Wrapped;
}
我不明白为什么编译器允许一个实际上是相同的东西而不是另一个。
【问题讨论】:
-
看起来编译器在协调解构类型时遇到了麻烦,即使它们在逻辑上是相同的。没有解构的替代解决方案将为您提供所需的结果。我建议坚持使用该解决方案。
-
您能给我们一些反馈吗?
标签: reactjs typescript