如何将HOC与Redux Compose和Typescript一起使用

时间:2019-01-24 20:49:23

标签: reactjs typescript redux compose

我有两个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);

1 个答案:

答案 0 :(得分:2)

在当前的打字稿类型系统中,我们无法为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