Loading...

How to define an enum in Typescript and use it in a Next.js app?

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

Creating an enum in TypeScript within a Next.js project is straightforward. Enums in TypeScript allow you to define a set of named constants that can be used to represent a collection of related values. Here’s how you can create and use an enum in a Next.js application:

Step-by-Step Guide

  1. Setup TypeScript in Next.js: If you haven’t already set up TypeScript in your Next.js project, create a tsconfig.json file at the root of your project and run the following command:
    npx next dev
    

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

  2. Define Your Enum: Create a new TypeScript file or add the enum to an existing file where you need it. For example, you can create an enums.ts file inside a types directory.

    // types/enums.ts
    export enum UserRole {
      Admin = 'ADMIN',
      User = 'USER',
      Guest = 'GUEST'
    }
    
  3. Using the Enum in a Component: Import and use the enum in your Next.js components or other TypeScript files.

    // app/page.tsx
    import { UserRole } from '../types/enums';
    
    const HomePage = () => {
      const role: UserRole = UserRole.Admin;
    
      return (
        <div>
          <h1>Welcome, {role}</h1>
        </div>
      );
    };
    
    export default HomePage;
    

Example Project Structure

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

Using Enums with Functions

You can also use enums in functions for better type safety and readability.

// types/enums.ts
export enum UserRole {
  Admin = 'ADMIN',
  User = 'USER',
  Guest = 'GUEST'
}

// utils/checkRole.ts
import { UserRole } from '../types/enums';

export const checkUserRole = (role: UserRole): string => {
  switch (role) {
    case UserRole.Admin:
      return 'You have admin privileges.';
    case UserRole.User:
      return 'You are a regular user.';
    case UserRole.Guest:
      return 'You are a guest.';
    default:
      return 'Unknown role.';
  }
};

// pages/index.tsx
import { UserRole } from '../types/enums';
import { checkUserRole } from '../utils/checkRole';

const HomePage = () => {
  const role: UserRole = UserRole.User;

  return (
    <div>
      <h1>Role Check: {checkUserRole(role)}</h1>
    </div>
  );
};

export default HomePage;

Including Enums in TypeScript Configuration

Ensure that your TypeScript configuration (tsconfig.json) includes all necessary files for compilation.

// tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

Summary

Creating and using enums in a Next.js TypeScript project involves defining the enum, exporting it, and then importing and using it where needed. This improves code readability, maintainability, and type safety.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on July 9, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

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.

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 react February 9, 2024 How to make an HTML button element behave like a Link component in Next.js?

In Next.js, you can use the Link component from next/link to create client-side navigation. However, if you want to use an HTML button element (<button>) to behave like a link, you can wrap it with the Link component. Here’s how you can do it:

Like my work?

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