如何在 redux compose 和 Typescript 中使用 HOC
How to use HOC with redux compose and Typescript
我有两个 HOC,想和 redux compose 一起使用,但是编译器没有生成正确的类型。 Compose 声明函数来自 redux source code. If we paste the code in the 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);
我们无法在当前的 typescript 类型系统中构建一个好的 compose 版本。无法将泛型类型参数捕获到 HOC。
我们可以根据擦除类型参数的方式创建一个在某些情况下可能有效的版本(在这种情况下,基本上它们只是被最窄的类型替换 {}
)。这意味着我们可以获得 HOC 添加的 props。我不知道它的效果如何,但它确实适用于您的示例:
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; }>
我有两个 HOC,想和 redux compose 一起使用,但是编译器没有生成正确的类型。 Compose 声明函数来自 redux source code. If we paste the code in the 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);
我们无法在当前的 typescript 类型系统中构建一个好的 compose 版本。无法将泛型类型参数捕获到 HOC。
我们可以根据擦除类型参数的方式创建一个在某些情况下可能有效的版本(在这种情况下,基本上它们只是被最窄的类型替换 {}
)。这意味着我们可以获得 HOC 添加的 props。我不知道它的效果如何,但它确实适用于您的示例:
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; }>