How to define type as props for component. I want to pass component to render inside my component and pass props as object for them with ts types checking.
Thx for help
CodePudding user response:
These props need to be generic, because you want to derive one type from the value of another within this type. And the generic parameter needs to be the type of the component, so that it's props may be inferred.
export interface IWindowProps<Component extends React.FC<any>> {
ComponentToRender: Component
ComponentToRenderProps: ComponentProps<Component>
}
And you would use those props with a generic component, so that the generic type parameter may be passed through to the props type.
function MyWindow<Component extends React.FC<any>>(props: IWindowProps<Component>) {
return <></>
}
Which you would use like so:
function Foo({ abc }: {abc: number}) {
return <h1>{abc}</h1>
}
// good
const test = <MyWindow ComponentToRender={Foo} ComponentToRenderProps={{ abc: 123 }} />
// error
const bad = <MyWindow ComponentToRender={Foo} ComponentToRenderProps={{ def: 123 }} />
That said, you may be better off with a props that accepts a React.ReactNode
instead, so you can render whatever you like in there instead.
For example:
export interface IWindowProps {
content: ReactNode
}
function MyWindow(props: IWindowProps) {
return <>{props.content}</>
}
function Foo({ abc }: {abc: number}) {
return <h1>{abc}</h1>
}
const test = <MyWindow content={<Foo abc={123} />} />
It's a lot simpler, and it's more flexible since you don't need to pass it a true component with props at all, any jsx fragment will do.