Open In App

Next.js TypeScript

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

NextJS is a powerful and popular JavaScript framework that is used for building server-rendered React applications. . It provides a development environment with built-in support for TypeScript, as well as a set of features that make it easy to build and deploy web applications. It was developed by Zeit and has gained widespread adoption due to its simplicity, performance, and extensibility. In this article, we will take a look at how to use TypeScript with NextJS to build high-quality and scalable applications.

TypeScript is a strict syntactical superset of JavaScript, which means that any valid JavaScript code is also a valid TypeScript code. However, TypeScript adds additional features such as static typing, classes, and interfaces, which can help developers write more maintainable and scalable code.

There are several benefits to using TypeScript with NextJS:

  • Improved Scalability: Large NextJS applications can benefit from the added structure and organization provided by TypeScript’s class and interface features. This can make it easier to manage and maintain complex codebases .
  • Improved Code Quality: TypeScript’s static typing allows developers to catch errors early in the development process and avoid runtime bugs. This can lead to higher-quality code and a better user experience.
  • Enhanced Productivity: TypeScript’s rich type system and powerful editor support (such as IntelliSense) can help developers write code faster and with fewer errors.

 

Steps to install next js with typescript

Step 1: Create a new directory for your project: 

mkdir my-proj

Step 2: Change into the new directory for your project: 

cd my-proj

Step 3: Initialize a new Next.js project that uses TypeScript by typing the following code :  

npx create-next-app . --template with-typescript

Setting Up the Configuration Files

To set up the Next.js TypeScript configuration, you can add a tsconfig.json file in the root of your project with the following contents:

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "jsx": "preserve",
        "lib": ["dom", "esnext"],
        "strict": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "sourceMap": true,
        "baseUrl": ".",
        "paths": {
            "~/*": ["./*"]
        }
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules"]
}

Project Structure:

 

The dependencies folder should look like:

 

Example 1:This example illustrates the use of a state variable in Next.js with TypeScript. In this example, we have a simple counter that increments by 1 every time the button is clicked. Add the following code to the ‘index.tsx’ file to the ‘pages’ directory in your project.

pages/index.tsx

Javascript




import { useState } from 'react'
import Head from 'next/head'
  
const Counter: React.FunctionComponent = () => {
    const [count, setCount] = useState(0)
  
    return (
        <div>
            <Head>
                <title>Counter</title>
            </Head>
            <h1 style={{ color: 'green' }}>
                GeeksforGeeks
            </h1>
            <h3>Counter Example</h3>
            <p>Count: {count}</p>
            <button onClick=
                {() => setCount(count + 1)}>
                Increment
            </button>
        </div>
    )
}
  
export default Counter;


To run the code type the following code in your terminal:

npm run dev

Output:

 

Example 2: This example illustrates the use of a form with input fields in Next.js with TypeScript. In this example, we have a simple form with two input fields for name and email, and a submit button. Add the following code to the ‘index.tsx’ file to the ‘pages’ directory in your project.

pages/index.tsx:

Javascript




import { useState } from 'react'
import Head from 'next/head'
  
const ContactForm: React.FunctionComponent = () => {
    const [form, setForm] = useState({ name: '', email: '' })
  
    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setForm({ ...form, [event.target.name]: event.target.value })
    }
  
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()
        alert(`Name: ${form.name} Email: ${form.email}`)
    }
  
    return (
        <div>
            <Head>
                <title>
                    Next.JS + TypeScript Example : Contact Form
                </title>
            </Head>
  
            <center>
                <h1 style={{ color: 'green' }}>
                    GeeksforGeeks
                </h1>
                <h3>Next.JS + TypeScript</h3>
            </center>
            <h5>Contact Form Example </h5>
            <form onSubmit={handleSubmit}>
                <label>
                    Name:
                    <input type="text" name="name" 
                        value={form.name} 
                        onChange={handleChange} />
                </label>
                <br />
                <label>
                    Email:
                    <input type="email" name="email" 
                        value={form.email} 
                        onChange={handleChange} />
                </label>
                <br />
                <button type="submit">Submit</button>
            </form>
        </div>
    )
}
  
export default ContactForm;


To run the code type the following code in your terminal:

npm run dev

Output:

 

Please go through How to add TypeScript in Next.js to know more about the Typescript and Next.js relation.

Reference: https://nextjs.org/docs/basic-features/typescript



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads