具有高阶函数的泛型

时间:2019-11-15 08:10:29

标签: reactjs typescript rxjs typescript-generics

我想创建一个为我现有的React中的一个返回构造函数的函数 组件。返回值是传入函数组件的自定义类扩展。

换句话说:

我的高阶函数withObservableStream()的返回值-它返回另一个 函数-接受现有的React组件(已输入道具)并返回新组件的构造函数 最终应将其呈现到DOM中。由于我只扩展了传入的组件 RxJS订阅,两个组件将共享相同的道具。

类型系统应:

  • 抱怨财产不匹配

我如何实现这一目标-谁能向我展示“遗传主义”的魔力?这可能吗?

type Props = Triggers & InitialState;

function App(props: Props) {
  return <button
  onClick={(event) => {
    props.onClick(event);
  }}
  >{props.text} (state: {props.counterX})</button>;
}

// still all good here:
const appInstance = App({...triggers, text: "init", counterX: -1});

const WrappedApp = withObservableStream(
  interval(5000).pipe(
    map((o) => ({counterX: o})),
  ),
  {...triggers},
  {
    // counterX: -1,
    text: "XXX",
  },
)(App);
// type sytem should complain meaningful here:
// 2nd & 3rd parameter of observableStream() should match the constructor signature of App (type Props)
// for both new WrappedApp(...) and render(<WrappedApp...)

stackblitz上的完整代码示例。

1 个答案:

答案 0 :(得分:1)

我修改了您的代码以添加所需的类型限制。 基本上,您需要将通用类型添加到withObservableStream的返回函数中:

withObservableStream.tsx

import React from "react";
import Observable from "rxjs";

export default <T extends Observable.Observable<any>, U, V>(observable: T, triggers: U, initialState: V) => {
  type cState = U & V;
  return function(Component: React.ComponentType<cState>) {

    return class extends React.Component<cState, V> {
      private subscription: any;

      constructor(props: cState) {
        console.log("got props", props);
        super(props);

        this.state = {
          ...initialState,
        };
        console.log(this.state);
      }

      public componentDidMount() {
        console.log("Subscribing...");
        this.subscription = observable.subscribe((newState) => {
          console.log("setting a new state...", newState);
          this.setState({ ...newState });
          console.log("state: ", this.state);
        });
      }

      public componentWillUnmount() {
        console.log("Unsubscribing...");
        this.subscription.unsubscribe();
      }


      public render() {
        return (
          <Component {...this.props} {...this.state} {...triggers} />
        );
      }
    }
  };
};

index.tsx

import React from "react";
import { render } from "react-dom";
import { interval } from "rxjs";
import { map } from "rxjs/operators";
import withObservableStream from "./withObservableStream";

type Triggers = {
  onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};

type InitialState = {
  text: string,
  counterX: number,
};

type Props = Triggers & InitialState;

export function App(props: Props) {
  return <button
  onClick={(event) => {
    props.onClick(event);
  }}
  >{props.text} (state: {props.counterX})</button>;
}

const triggers: Triggers = { onClick: () => console.log("clicked!!!") };

const appInstance = App({...triggers, text: "init", counterX: -1});
render(appInstance, document.getElementById("root1"));

const WrappedApp = withObservableStream(
  interval(5000).pipe(
    map((o) => ({counterX: o})),
  ),
  {...triggers},
  {
    counterX: -1,
    text: "XXX",
  },
)(App);

const appInstance2 = new WrappedApp({...triggers, counterX: -1, text: "23"});

render(<WrappedApp {...triggers} counterX={-1} text="23"/>,  document.getElementById("root1"))
document.getElementById("root2"));

在此处查看运行代码:stackblitz