When using Typescript with Next.js, you may have to set types for a single page or a functional component in Next.js. You can do that by importing the NextPage
type from the next
module and then setting it as the type for a page or functional components.
For example, let's say we want to set the type for the index page (or index.tsx
file) in Next.js. First, we have to import the NextPage
type from the Next.js module like this,
// import NextPage type from nextjs
import { NextPage } from "next";
Now we can use the NextPage
type on our index.tsx
file like this,
// import NextPage type from nextjs
import { NextPage } from "next";
// setting type for index page
const IndexPage: NextPage = () => {
return <h1>Hello World!</h1>;
};
// exporting IndexPage as default export
export default IndexPage;
This same approach can be used for any functional components in Next.js.
See the above code live in codesandbox
That's all 😃!
Top comments (0)