Skip to content

Instantly share code, notes, and snippets.

@xenohunter
Created June 1, 2023 19:15
Show Gist options
  • Save xenohunter/2845aac6dc59ec0ddc1d69703d2c32c3 to your computer and use it in GitHub Desktop.
Save xenohunter/2845aac6dc59ec0ddc1d69703d2c32c3 to your computer and use it in GitHub Desktop.
Type checking of a component-props pair in TypeScript
import React from "react";
import WrapperComponent from "./WrapperComponent";
import SomeOtherComponent from "./SomeOtherComponent";
const ComponentPropsPair = () = {
return (
<>
<div>...</div>
<WrapperComponent
// You want type check to work for `contentComponent` and `contentProps`
contentComponent={SomeOtherComponent}
contentProps={{
someOtherComponentProp1: "abc",
someOtherComponentProp2: 123,
}}
>
<button>Triggers the container with SomeOtherComponent in it to open</button>
</WrapperComponent>
<div>...</div>
</>
);
};
export default ComponentPropsPair;
import React from "react";
import { DynamicWrapper, WrappedComponentProps } from "./types";
type ComponentWrapperProps<T extends WrappedComponentProps> = DynamicWrapper<T> & {
children: React.ReactNode;
};
const ComponentWrapper = <T extends WrappedComponentProps>({
children,
contentComponent,
contentProps,
}: ComponentWrapperProps<T>) = {
const ContentComponent = contentComponent;
return (
<Container>
<TriggerLogic>{children}</TriggerLogic>
<ContentWrapper>
<ContentComponent {...contentProps} />
</ContentWrapper>
</Container>
);
};
export default ComponentWrapper;
export type WrappedComponentProps = React.ComponentProps<any>;
export type DynamicWrapper<T extends WrappedComponentProps> = {
contentComponent: React.ComponentType<T>;
contentProps: T & Object;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment