【问题标题】:React HOC and TypeScript 3.2React HOC 和 TypeScript 3.2
【发布时间】:2019-05-02 12:40:24
【问题描述】:

随着 TypeScript 在 v3.2 中改进其 JSX 类型检查,我们现在无法正确键入我们的 HOC。

有人可以为 TypeScript 3.2 修复以下 HOC 中的类型吗?

import { ComponentType } from 'react';

type Props = { custom: string };
type Omit<T, K extends string> = Pick<T, Exclude<keyof T, K>>;

function hoc<P extends Props>(Component: ComponentType<P>) {
  return (props: Omit<P, keyof Props>) => {
    return <Component {...props} custom="text" />;
  }
}

TypeScript 错误:

Type '{ custom: string; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Property 'custom' does not exist on type 'IntrinsicAttributes & P & { children?: ReactNode; }'

基本上,这个想法是将需要“自定义”属性的组件转换为不再需要它的组件,因为它将由 HOC 自动注入。

编辑: 可能是同一个问题:https://github.com/Microsoft/TypeScript/issues/28748

【问题讨论】:

  • 我对新的 TS 3.2.1 有同样的问题,我认为这是一个错误。

标签: javascript reactjs typescript higher-order-components


【解决方案1】:

我确定这不是您希望的答案,但您可以通过将内部函数中的 props 类型更改为 any 并将 Omit 类型放入外部函数的返回类型注解,像这样:

function hoc<P extends Props>(Component: ComponentType<P>): ComponentType<Omit<P, keyof Props>> {
  return (props: any) => {
    return <Component {...props} custom="text" />;
  }
}

【讨论】:

  • 我将props 的转换推迟到any 直到传播,所以我使用了{(...this.props as any)},所以你仍然可以在渲染函数的其他地方使用键入的props。到目前为止,最无干扰的解决方案。谢谢...
  • 这个答案的问题在于,您返回的组件不会对其道具进行类型检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 2019-01-22
  • 2018-11-09
  • 2023-03-04
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多