如何在 redux compose 和 Typescript 中使用 HOC [英] How to use HOC with redux compose and Typescript

查看:27
本文介绍了如何在 redux compose 和 Typescript 中使用 HOC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two HOC, which want to use with redux compose, but the compiler doesn't make correct type. Compose declares function is from redux source code. If we paste the code in the playground. We will see different types of first and second variables.

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);

推荐答案

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

We can't model a good version of compose in the current typescript type system. There is no way to capture generic type parameters to the HOCs.

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

We can create a version that might work in some circumstances based on the way the type parameters get erased (basically they are just replaced with the narrowest type in this case {}). This means we can get the props that are added by the HOC. I don't know how well this will work, but it does work for your sample:

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; }>

游乐场链接

这篇关于如何在 redux compose 和 Typescript 中使用 HOC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆