Ad

Generics With Higher Order Function

I want to create a function that returns a constructor function for one of my existing React components. The return value is a customized class extension of the passed-in function component.

With other words:

The return value of my higher-order function withObservableStream() - it returns another function - takes an existing React component (which has typed props) and returns a constructor function of a new one which should be eventually rendered into the DOM. Since I am only extending the passed in component with an RxJS subscription both components will share identical props.

The type system should:

  • Complain about a property mismatch

How can I achieve that - who can show me the magic of 'genericism'? Is this possible?

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

Full code sample on stackblitz.

Ad

Answer

I modified your code to add the desired type restriction. Basically you need to add generic types down to the returned functions of 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"));

Check out running code here: stackblitz.

Ad
source: stackoverflow.com
Ad