用TypeScript反应HOC:可以用不同的约束子类型实例化

时间:2020-01-11 17:08:47

标签: reactjs typescript typescript-generics

我想做的是编写一个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

但对如何表达它还不甚了解。

1 个答案:

答案 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;
  }