'Type error when using function with the return type NextPage
So the following code works:
const HomePage: NextPage = () => (
<div>
<div>HomePage</div>
</div>
);
However I would like to comply with the Airbnb's style guide, which in this case requires you to use a named function, arriving at this code:
function HomePage(): NextPage {
return (
<div>
<div>HomePage</div>
</div>
)
}
However the compiler gives the following error to the code above:
Type 'Element' is not assignable to type 'NextPage<{}, {}>'.
Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}>'.
Type 'ReactElement<any, any>' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.ts(2322)
I can bypass the error by either not specifying the type, or by casting the return to as unknown as NextPage, both of which look like workarounds rather than a correct solution.
What is the correct way of using named functions in this case?
Solution 1:[1]
use React.FC type instead of NextPage
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lakshan Bandara |
