I want to define the type of component. It doesn’t matter how many props it receives, is it a class or a function component, I don’t even care if it returns a JSX element or just null or any string.
All I want to say is "a component", which is defined by React as anything that may have a key prop and a ref prop. I tried using React.Component:
function Ramadan(){
return <></>
}
const templatesMap: { [key: string]: React.Component } = {
ramadan: Ramadan,
adha: () => <></>,
fitir: () => <></>,
unset: () => <></>,
mothers: () => <></>,
birthDay: () => <></>,
}
but TypeScript is showing the following error:
Type '() => Element' is not assignable to type 'Component<{}, {}, any>'.ts(2322)
WriteContent.tsx(10, 25): The expected type comes from this index signature.
>Solution :
You could use React.ComponentType which is typed as:
React.ComponentClass<P, any> | React.FunctionComponent<P>
Example:
function Ramadan(){
return <></>
}
const templatesMap: { [key: string]: React.ComponentType<any> } = {
ramadan: Ramadan,
adha: () => <></>,
fitir: React.forwardRef((props, ref) => <></>),
unset: class MyClassComp extends React.Component {
render() { return <></> }
},
mothers: () => null,
birthDay: () => <></>,
}