使用完整类型检查来响应Typescript Context API HOC

时间:2018-12-19 13:43:17

标签: reactjs typescript higher-order-components react-context

所以我当前正在为react context API编写一个HOC,它将组件包装在context api使用者中。

我的要求是:

  1. 需要对道具进行全面检查
  2. 在添加上下文api作为道具之前,我需要能够对上下文api提供的状态进行子集化(这也需要完整类型检查)

我当前拥有的代码是这个(使用实用程序类型库):

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

组件:

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和Intersection从实用程序类型导入并在此处定义: https://github.com/piotrwitek/utility-types

如果我可以稍微简化一下,或者在将回调的默认值设置为Y之前不必将状态强制转换为未知状态,那将是很棒的事情。

有什么想法吗?

谢谢!

0 个答案:

没有答案