【问题标题】:How to use HOC with redux compose and Typescript如何将 HOC 与 redux compose 和 Typescript 一起使用
【发布时间】:2019-06-18 16:29:57
【问题描述】:

我有两个 HOC,想与 redux compose 一起使用,但编译器没有生成正确的类型。 Compose 声明函数来自 redux source code。如果我们将代码粘贴到playground。我们将看到不同类型的第一和第二变量。

type Func1<T1, R> = (a1: T1) => R

type Component<Props> = (props: Props) => string;

declare function compose<T1, A, R>(
  f1: (b: A) => R,
  f2: Func1<T1, A>
): Func1<T1, R>

declare const HOC1: <Props>(component: Component<Props>)
    => Component<Props & { prop: string }>

declare const HOC2: <Props>(component: Component<Props>)
    => Component<Props & { prop: number }>

declare const component: Component<{props: boolean}>

const first = HOC1(HOC2(component));

const second = compose(HOC1, HOC2)(component);

【问题讨论】:

  • 你的游乐场链接坏了,只是一个游乐场链接,没有代码
  • @TitianCernicova-Dragomir 抱歉,我已经更新了链接。
  • 我认为我们不能在当前的 typescript 类型系统中为 compose 建模一个好的版本。无法将泛型类型参数捕获到 HOC。这可能适用于您非常具体的情况,但它不是一个真正的通用解决方案:declare function compose&lt;A, R, R2&gt;(f1: (b: A) =&gt; R,f2: (b: A) =&gt; R2,): (&lt;P&gt;(c: Component&lt;P&gt;) =&gt; Component&lt;P &amp; R &amp; R2&gt;)
  • @TitianCernicova-Dragomir 很伤心。请单独发布您的答案,我会检查它是否正确。
  • 添加了答案,10x

标签: reactjs typescript redux


【解决方案1】:

我们无法在当前的 typescript 类型系统中为一个好的 compose 版本建模。无法将泛型类型参数捕获到 HOC。

我们可以根据类型参数被擦除的方式创建一个可能在某些情况下工作的版本(基本上它们只是在这种情况下被替换为最窄的类型{})。这意味着我们可以获得 HOC 添加的道具。我不知道这会有多好,但它确实适用于您的示例:

type Func1<T1, R> = (a1: T1) => R

type Component<Props> = (props: Props) => string;

declare function compose<A, R, R2>(f1: (b: A) => Component<R>,f2: (b: A) => Component<R2>,): (<P>(c: Component<P>) => Component<P & R & R2>)

declare const HOC1: <Props>(component: Component<Props>)
    => Component<Props & { prop1: string }>

declare const HOC2: <Props>(component: Component<Props>)
    => Component<Props & { prop2: number }>

declare const component: Component<{props3: boolean}>

const a = HOC1(HOC2(component));

const b = compose(HOC1, HOC2)(component); //Component<{ props3: boolean; } & { prop1: string; } & { prop2: number; }>

Playground link

【讨论】:

猜你喜欢
  • 2020-01-08
  • 2021-04-03
  • 2018-11-09
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多