Loading...

How to create custom types in Typescript in a Next.js app?

question nextjs react
Ram Patra Published on July 9, 2024
Tested on Next.js 14

Declaring custom types in TypeScript for a Next.js application involves creating type definitions that can be used across your project to ensure type safety and better code management. Here are the steps to declare and use custom types in a Next.js app:

Step-by-Step Guide

  1. Setup TypeScript in Next.js: If you haven’t already set up TypeScript in your Next.js project, you can do so by creating a tsconfig.json file at the root of your project and running the following command:

    npx next dev
    

    This will automatically set up the basic TypeScript configuration for you.

  2. Create a Types Directory: Create a directory to store your custom types. This is typically done in a folder named types at the root of your project.

    mkdir types
    
  3. Define Your Custom Types: Create a new TypeScript file inside the types directory. For example, you can create a types.ts file and define your custom types there.

    // types/types.ts
    export interface User {
      id: number;
      name: string;
      email: string;
    }
    
    export type UserRole = 'admin' | 'user' | 'guest';
    
  4. Using Custom Types in Your Components: Import and use these types in your Next.js components or other TypeScript files.

    // app/page.tsx
    import { User, UserRole } from '../types/types';
    
    const HomePage = () => {
      const user: User = {
        id: 1,
        name: 'John Doe',
        email: '[email protected]'
      };
    
      const role: UserRole = 'admin';
    
      return (
        <div>
          <h1>Welcome, {user.name}</h1>
          <p>Your role is: {role}</p>
        </div>
      );
    };
    
    export default HomePage;
    
  5. (Optional) Configure Path Aliases: To make imports cleaner, you can configure path aliases in your tsconfig.json.

    // tsconfig.json
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@types/*": ["types/*"]
        }
      }
    }
    

    After configuring the path aliases, you can import the types like this:

    // pages/index.tsx
    import { User, UserRole } from '@types/types';
    
    const HomePage = () => {
      // ...rest of the code
    };
    
  6. Re-run the Development Server: Make sure to restart your Next.js development server to apply the TypeScript configurations.

Example Project Structure

my-nextjs-app/
├── app/
│   ├── page.tsx
├── types/
│   └── types.ts
├── tsconfig.json
└── package.json

By following these steps, you can effectively declare and use custom types in your Next.js application with TypeScript, improving type safety and code quality.

For defining global types in a Next.js app, read this blog.

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on July 9, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question nextjs vercel March 1, 2025 Three ways to disable Image Optimization in Vercel

If you’re using the free tier of Vercel, like I do for some of my small side projects, you will get the 402 Payment Required error eventually when loading images. This is because you have hit the Image Optimization limit of the free plan. The solution to this is to disable Vercel’s Image Optimization, or to host the images elsewhere, or to upgrade to their Pro plan.

question nextjs front-end December 21, 2024 Difference between router in next/navigation and next/router in Next.js?

In Next.js, there are two main ways to handle routing programmatically:

question typescript react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.