Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • jQuery
  • AngularJS
  • ReactJS
  • Next.js
  • React Native
  • NodeJS
  • Express.js
  • MongoDB
  • MERN Stack
  • PHP
  • WordPress
  • Bootstrap
  • Tailwind
  • CSS Frameworks
  • JS Frameworks
  • Web Development
Open In App
Next Article:
How to Use NextJS in Typescript?
Next article icon

How to add TypeScript in Next.js ?

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to add TypeScript in Next.js.

Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in the project and quick debugging of the project.

Approaches: There are two ways to add TypeScript in Next.js, depending upon the use case of the user:

  • Add TypeScript using create-next-app CLI
  • Add TypeScript to an existing project

1. Add TypeScript using create-next-app CLI:

Creating Next.js application: Follow the below steps to create the application:

Step 1: You can add TypeScript right when the Next.js app is created by adding the –typescript or –ts flag in the create-next-app CLI. The command to do so is given below.

npx create-next-app my-project --typescript
# or
npx create-next-app my-project --ts
# or
yarn create next-app my-project --typescript

Project Structure: The file structure of the newly created Next.js app would look like the figure shown below

 

Note: The –typescript flag also installs ESLint in the project.

The package.json has all the dependencies and dev dependencies installed.

"dependencies": {
"next": "12.1.6",
"react": "18.1.0",
"react-dom": "18.1.0"
},
"devDependencies": {
"@types/node": "^17.0.42",
"@types/react": "^18.0.12",
"eslint": "8.17.0",
"eslint-config-next": "12.1.6",
"typescript": "^4.7.3"
}
  • @types/node, @types/react, and @types/react-dom are type definitions for the respective packages. 
  • eslint and eslint-config-next are required to run ESLint in the project.
  • typescript dependency is also installed. So now we can start creating our TypeScript files.

Example: Consider the code snippet of the index.tsx file below. Here the type of state counter is explicitly specified to be a number. 

pages/index.tsx
import { useState } from "react"; import CounterButton from "../components/CounterButton";  export default function Home() {     const [counter, setCounter] = useState<number>(0);      return (         <div>             <CounterButton setCounter={setCounter}                  value={-1} />             <h1>{counter}</h1>             <CounterButton setCounter={setCounter}                  value={1} />         </div>     ); } 

Create a new folder called components at the root directory of the project. Create a new file CounterButton.tsx and paste the code given below into that file.

components/CounterButton.tsx
import { Dispatch, SetStateAction } from "react";  interface IProps {     value: number;     setCounter: Dispatch<SetStateAction<number>>; }  export default function CounterButton({ value,      setCounter }: IProps) {     const handleCounter = () => {         setCounter((prev) => prev + value);     };      return (         <button onClick={handleCounter}>             {value === 1 ? "Increment" : "Decrement"}         </button>     ); } 

Here we are destructuring the props. The props have to be of the type IProps to work without any errors. Setting the type of props helps in auto-completion and helps to avoid any bugs. If any prop has a mismatched type, the editor will show errors and the application will not work.

Steps to run the application: Run the application using the command given below

npm run dev
# or
yarn dev

Output:

 

2. Add TypeScript to an existing project:

Add TypeScript to Application: Follow the steps given below to add TypeScript to add to your existing project

Step 1: Create a tsconfig.json file: Each TypeScript project requires a tsconfig.json file that contains all the rules and configuration of TypeScript. Create the tsconfig.json file by entering the below command at the root directory of your Next.js project in your terminal.

touch tsconfig.json

By default, the tsconfig.json file is empty.

Step 2: Install dependencies: Write the below commands in the terminal to install all the dependencies:

npm install -D typescript @types/react @types/node
# or
yarn add --dev typescript @types/react @types/node

Step 3: Populate tsconfig.json: After installing all the dependencies, run the app using

npm run dev
# or
yarn dev

It populates the tsconfig.json with basic rules and configurations. The configurations can be changed, based on the user’s choice. Check this site to know more about tsconfig rules and configurations.

Note: Add the “moduleResolution” rule under the compilerOptions object as shown below, if it is absent from your tsconfig file.

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",

// Add the rule below
"moduleResolution": "node",

"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}

Step 4: Rename the extensions of all the JavaScript files from .js to.ts. Change the extensions of all pages and components from .js/.jsx to .tsx.

Project Structure: Your project structure after following all the above steps should look like this:

Example: Consider the code snippet given below. The event for input change has a type “ChangeEvent<HTMLInputElement>” that helps in auto-completion of the code.

  • pages/index.tsx
JavaScript
import { ChangeEvent, useState } from "react";  export default function Home() {     const [input, setInput] = useState("");      const handleChange = (e: ChangeEvent<HTMLInputElement>) => {         setInput(e.target.value);     };      return (         <div>             <input type="text" value={input}                 onChange={handleChange} />             <h2>{input}</h2>         </div>     ); } 

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20240729164255/autocomplete.mp4

In the output above, it can be seen that as we entered e. in the setInput() function in the handleChange() function, a dropdown of all the possible suggestions pops up. This is not possible in JavaScript files. But TypeScript provides easy development by suggesting auto-completions and indicating errors. Furthermore, it can be seen that as we have completed typing e.target, another dropdown pops up again showing the possible suggestions.



Next Article
How to Use NextJS in Typescript?

A

ankitk26
Improve
Article Tags :
  • Web Technologies

Similar Reads

  • How to Add Tweets in Next.js ?
    Adding tweets in Next.js involves using Twitter's embed feature or API to display tweets. You can embed tweets directly in components or fetch and display them using server-side rendering or client-side data fetching. In this article, we are going to learn how we can add Tweets in NextJs. ApproachTo
    2 min read
  • How to add Typewriter effect in Next.js ?
    In this article, we are going to learn how we can add the Typewriter effect in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS component
    2 min read
  • How to Use NextJS in Typescript?
    TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
    5 min read
  • How to add Timer in Next.js ?
    In this article, we are going to learn how we can add Timer in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
    2 min read
  • How to install TypeScript ?
    TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
    3 min read
  • How to Add Stylesheet in Next.js ?
    In Next.js, adding a stylesheet enhances your app's styling capabilities. Import CSS files directly in your components or pages using ES6 import syntax. Next.js optimizes and includes these styles in the build process, ensuring efficient and modular CSS management. In this post, we are going to lear
    4 min read
  • How to Setup a TypeScript Project?
    In the world of modern web development, TypeScript has emerged as a powerful superset of JavaScript, offering static typing and improved tooling. Its strong typing system helps developers catch errors early during development, leading to more maintainable and scalable code. Whether you're starting a
    2 min read
  • How to add Youtube Videos in Next.js ?
    In this article, we are going to learn how we can add Youtube Video in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components condit
    2 min read
  • How to add Web Share in Next.js ?
    The Web Share API enables web applications to share content (like URLs, text, or files) to other apps installed on a user's device, such as social media platforms, messaging apps, or email clients. Integrating the Web Share API into a Next.js project enhances user experience by providing a seamless
    2 min read
  • How to add Slider in Next.js ?
    Adding a slider in Next.js involves integrating a slider component, like react-range, managing its state using React hooks and applying styles for customization, enhancing user interaction and input precision in your application. ApproachTo add our Slider we are going to use the react-range package.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences