import { ComponentType } from "react"; import { Fn } from "../types/Fn"; import { Hoc } from "../types/Hoc"; type WithHocsArg = | Hoc | ((Component: ComponentType) => ComponentType); type WithHocsFlat< Hocs extends WithHocsArg[], Acc extends Fn[] = [], > = Hocs extends [infer first, ...infer rest extends WithHocsArg[]] ? first extends Hoc ? WithHocsFlat : WithHocsFlat : Acc; /** * Apply multiple hocs * * @example * const NewComponent = withHocs([withWrapper(A), withWrapper(B)])(MyComponent) * * * * * * * @example * const MyComponent = (() => { * function MyComponent(props: { ... }) { * return ; * } * return withHocs([ ... ])(MyComponent); * })(); * * @example * import { withHoc1, withHoc1 } from 'my-hocs' * // `withHoc1_2` can be used somewhere else * export const withHoc1_2 = withHocs([withHoc1, withHoc2]) */ export function withHocs( hocs: Hocs, ): Hoc> { return (arg: any) => hocs.reduceRight((Component, hoc) => hoc(Component), arg); }