Created
June 1, 2023 19:15
-
-
Save xenohunter/2845aac6dc59ec0ddc1d69703d2c32c3 to your computer and use it in GitHub Desktop.
Type checking of a component-props pair in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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