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

Unf*_*ing 5 compose-db typescript reactjs redux

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

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);
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 5

我们无法在当前的打字稿类型系统中为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; }>
Run Code Online (Sandbox Code Playgroud)

游乐场链接