我想做的是编写一个HOC,该HOC包装具有强制属性value
的组件,但不通过其自身的属性name
import React, { ComponentType } from 'react';
interface IPassThroughProps {
value: string;
}
interface IHocPropsType {
name: string;
}
export function hoc<PropsType extends IPassThroughProps>(
Component: ComponentType<PropsType>
): ComponentType<IHocPropsType & PropsType> {
const hoc = ({ name, ...props }: IHocPropsType & PropsType): JSX.Element => (
<Component {...props} />
);
return hoc;
}
问题是生成键入错误:
类型
Pick<IHocPropsType & PropsType, Exclude<keyof PropsType, "name">>
不能分配给类型IntrinsicAttributes & PropsType & { children?: ReactNode; }
。类型
Pick<IHocPropsType & PropsType, Exclude<keyof PropsType, "name">>
不能分配给类型PropsType
。
Pick<IHocPropsType & PropsType, Exclude<keyof PropsType, "name">>
可分配给类型PropsType
的约束,但是PropsType
可以用约束IPassThroughProps
的另一子类型实例化。
关于如何修复它的任何建议?
我想我需要做一些事情:
IHocPropsType & PropsType
但对如何表达它还不甚了解。
答案 0 :(得分:1)
修复该问题的一种正确方法是使用...props
实用程序进行Omit
的类型转换:
import React, { ComponentType } from 'react';
interface IPassThroughProps {
value: string;
}
interface IHocPropsType {
name: string;
}
export function hoc<PropsType extends IPassThroughProps>(
Component: ComponentType<PropsType>
): ComponentType<IHocPropsType & Omit<PropsType, 'name'>> => {
const hoc = (
{ name, ...props }: IHocPropsType & Omit<PropsType, 'name'>
): JSX.Element => (
<Component {...(props as PropsType)} />
);
return hoc;
}