React Typescript Context API HOC with full type checking

Viewed 704

so I'm currently writing a HOC for the react context API which will wrap components in context api consumers.

My requirements are:

  1. Full type checking on props needs to be maintained
  2. I need to be able to subset the state provided by the context api before adding it as a prop (this also needs full type checking)

The code I currently have is this (using the utility-types library):

HOC:

export const withMainContext = <
T extends object,
X extends object,
Y = Intersection<Required<IAppContext>, X>,
Z = Diff<T, Required<IAppContext>>
>(
    Component: React.ComponentType<T>,
    subsetStateCallback: (state: IAppContext) => Y = 
        (state) => state as unknown as Y
  ): React.SFC<Z> => (props: Z) => {
      return <AppContext.Consumer>
        {(state: IAppContext) => {
            const newState = subsetStateCallback(state)
            return <Component {...props} {...newState}/>
        }}
        </AppContext.Consumer>
  }

Component:

interface ItestOtherProps {
     one: string;
     two: number;
     three: string;
}
type ItestAppProps = Required<Pick<IAppContext, 'workflows'>>

type ITestProps = ItestOtherProps & ItestAppProps

class Test extends React.Component<ITestProps, {}> {
     public render(): JSX.Element {
         return null
     }
}

const Testy = withMainContext<ITestProps, ItestAppProps>(
     Test,
     (state: Required<IAppContext>): ItestAppProps => {return {workflows: state.workflows}}
)


const useTesty = () => {
     return <Testy one={""} two={0} three={""}/>
}

Diff and Intersection are imported from utility-types and defined here: https://github.com/piotrwitek/utility-types

It would be awesome if I could simplify this a little, or not have to cast state as unknown before setting it to Y in the default for the callback.

Any ideas?

Thanks!

0 Answers
Related