【问题标题】:How to properly declare type for React wrapper component (HOC) using Typescript如何使用 Typescript 正确声明 React 包装器组件 (HOC) 的类型
【发布时间】:2021-07-20 13:55:12
【问题描述】:

我正在尝试实现一个简单的 HOC,以使用自定义工具提示来增强组件。虽然代码工作正常,但我无法弄清楚如何正确声明类型。 我的 HOC 的简化版本如下所示:

const withTooltip = <P extends {}>(
  BaseComponent: React.ComponentType<P>
): React.FC<P & { title?: string }> => ({ title, ...rest }) => {
  
  return (
    <>
      <BaseComponent {...rest} />
      <Tooltip title={title}/>
    </>
  );
};

但我收到了 Typescript 错误:

Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
  Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'P'.
    'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{}'.

如何正确声明此类 HOC 的类型?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你需要使用推断出的rest props的类型:

    import React, { ComponentType } from 'react'
    
    const Tooltip = (props: { title?: string }) => null
    
    type OptionalTitle = { title?: string };
    
    const withTooltip = <P extends object = object>(
      BaseComponent: ComponentType<Omit<P & OptionalTitle, "title">>
    ): React.FC<P & OptionalTitle> => ({ title, ...rest }) => {
    
      return (
        <>
          <BaseComponent {...rest} />
          <Tooltip title={title} />
        </>
      );
    };
    

    【讨论】:

    • 很遗憾,这个解决方案不起作用
    • 请检查链接,我没有任何错误
    • 抱歉没有更具体。是的,此解决方案不会导致错误。但是当我尝试在应用程序中使用这个 HOC 时,Typescript 似乎将包装组件的类型推断为简单的React.FC&lt;OptionalTitle&gt;,我需要明确显示正确的类型,例如:withTooltip&lt;ComponentProps&lt;typeof SomeComponent&gt;&gt;(SomeComponent)
    • 能否请您在玩具答案中提供示例。对我来说会容易得多
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2016-07-22
    • 2021-09-25
    • 2020-09-19
    • 1970-01-01
    • 2019-04-30
    相关资源
    最近更新 更多