DEV Community

Cover image for How to set typescript types for a page or a functional component in Next.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to set typescript types for a page or a functional component in Next.js?

Originally posted here!

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";
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

This same approach can be used for any functional components in Next.js.

See the above code live in codesandbox

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)