Skip to content

Instantly share code, notes, and snippets.

@thehappybug
Created June 15, 2018 19:05
Show Gist options
  • Star 48 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save thehappybug/88342c122cfb1df9f14c9a10fb4926e4 to your computer and use it in GitHub Desktop.
Save thehappybug/88342c122cfb1df9f14c9a10fb4926e4 to your computer and use it in GitHub Desktop.
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export function withAppContext<
P extends { appContext?: AppContextInterface },
R = Omit<P, 'appContext'>
>(
Component: React.ComponentClass<P> | React.StatelessComponent<P>
): React.SFC<R> {
return function BoundComponent(props: R) {
return (
<AppContextConsumer>
{value => <Component {...props} appContext={value} />}
</AppContextConsumer>
);
};
}
@jasp402
Copy link

jasp402 commented Jul 7, 2019

I have a error.
Type 'R & { appContext: AppContextInterface; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Type 'R & { appContext: AppContextInterface; }' is not assignable to type 'P'. TS2322

    25 |     return (
    26 |       <AppContextConsumer>
  > 27 |         {value => <Component {...props} appContext={value} />}
       |                    ^
    28 |       </AppContextConsumer>
    29 |     );
    30 |   };

@gchumillas
Copy link

Try writing <Component {...props as P} appContext={value} />.

@thisroot
Copy link

Try writing <Component {...props as P} appContext={value} />.

Can't work for me

Conversion of type 'R' to type 'P' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  'R' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{ appContext?: AppContextInterface | undefined; }'.ts(2352)

@zokypesch
Copy link

guys do you have some updates for fixing this ???

@Joshhua5
Copy link

Joshhua5 commented Apr 6, 2020

I was able to get this working as of React 16.12

import GlobalContext, {ContextConsumer} from "../Props/GlobalContext";
import React, {FunctionComponent} from "react";

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

export function WithContext<
    P extends { global?: GlobalContext },
    R = Omit<P, 'global'>
    >(
    Component: React.ComponentClass<P> | FunctionComponent<P>
): FunctionComponent<R> {
    return function BoundComponent(props: R) {
        return (
            <ContextConsumer>
                {value => value && <Component {...props as unknown as P} global={value} />}
            </ContextConsumer>
        );
    };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment