website-logomedCode

How Start use Typescript with Next.js project

Explore the seamless transition from JavaScript to TypeScript in your Next.js application with our comprehensive guide. Learn the step-by-step process of integrating TypeScript, unlocking enhanced typ...
MOHAMMED DAKIR| October 28, 2023
next.js
How Start use Typescript with Next.js project

#dev #nextjs #javascript #tools #typescript

What is Next.js?

Next.js is a production-ready framework built on top of React and Node.js. It ships with all the features listed above and more. You can use Next.js to build static and dynamic apps since it supports client and server-side rendering. Next.js v9 introduced API routes, which allow you to extend your Next app with a real backend (serverless) built with Node.jsExpress.jsGraphQL, and so on.

Next.js uses automatic code-splitting (lazy loading) to render only the JavaScript needed for your app. Next.js can also pre-render your pages at build time to serve on demand, which can make your app feel snappy because the browser does not have to spend time executing the JavaScript bundle to generate the HTML for your app. This makes it possible for more search engine crawlers to index your app, which is great for SEO.

What is TypeScript?

TypeScript is a popular language created and maintained by Microsoft. It’s a superset of JavaScript, which means all valid JavaScript is valid TypeScript. You can convert your existing JavaScript app to TypeScript, and it should work as expected, as long as your code is valid JavaScript. TypeScript allows you to set types on your variables and functions so you can type-check your code statically and catch errors at compile time.

You can also use modern features that are not yet supported in JavaScript. And, don’t worry about browser support — TypeScript compiles to plain JavaScript, which means your TypeScript code will never ship in the browser.

Why should you use Next.js with TypeScript?

Using Next.js with TypeScript is a powerful combination that offers a range of benefits for developers, ultimately enhancing their experience and the quality of the applications they create. Here’s why you should consider using Next.js with TypeScript, accompanied by some feelings and examples.

  • Better developer experience
  • Scalability
  • Improved code quality

Using TypeScript in a Next.js app:

running the command below:

npx create-next-app next-typescript-example

Adding TypeScript to an existing project

Before we create our Next.js application, let’s look at how you can add TypeScript to your existing Next.js project. First, install the required dependencies with the command below:

npm install --save-dev typescript @types/react @types/node

Next, create a tsconfig.json file in the root directory of your project that will contain the TypeScript configurations for your project. Add the configurations below to the tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

Next, update the content of the file next.config.js file to use TypeScript with the code snippet below:

Creating TypeScript types in Next.js

// types/index.ts
export interface IPost {
  id: number
  title: string
  body: string
}

Creating components in Next.js

// components/AddPost.tsx


import * as React from 'react'
type Props = {
  savePost: (e: React.FormEvent, formData: IPost) => void
}
const AddPost: React.FC<Props> = ({ savePost }) => {
  const [formData, setFormData] = React.useState<IPost>()
  const handleForm = (e: React.FormEvent<HTMLInputElement>): void => {
    setFormData((prevState) => ({
      ...prevState,
      [e.currentTarget?.id]: e.currentTarget?.value,
    } as IPost));
  };
  return (
    <form className='Form' onSubmit={(e) => savePost(e, formData as IPost)}>
      <div>
        <div className='Form--field'>
          <label htmlFor='name'>Title</label>
          <input onChange={handleForm} type='text' id='title' />
        </div>
        <div className='Form--field'>
          <label htmlFor='body'>Description</label>
          <input onChange={handleForm} type='text' id='body' />
        </div>
      </div>
      <button
        className='Form__button'
        disabled={formData === undefined ? true : false}
      >
        Add Post
      </button>
    </form>
  )
}
export default AddPost

As you can see, we are using the IPost type without importing it into the file. After that, we create another type named Props that mirrors the props received as a parameter by the component. Next, we set the type IPost on the useState Hook. Then, we use it to handle the form data.

Once the form is submitted, we rely on the function savePost to save the data on the array of posts. Now, we can create and save a new post. Let’s move on to the component responsible for displaying the Post object. Refer to the following code:

// components/AddPost.jsx


import * as React from 'react'
type Props = {
  savePost: (e: React.FormEvent, formData: IPost) => void
}
const AddPost: React.FC<Props> = ({ savePost }) => {
  const [formData, setFormData] = React.useState<IPost>()
  const handleForm = (e: React.FormEvent<HTMLInputElement>): void => {
    setFormData((prevState) => ({
      ...prevState,
      [e.currentTarget?.id]: e.currentTarget?.value,
    } as IPost));
  };
  return (
    <form className='Form' onSubmit={(e) => savePost(e, formData as IPost)}>
      <div>
        <div className='Form--field'>
          <label htmlFor='name'>Title</label>
          <input onChange={handleForm} type='text' id='title' />
        </div>
        <div className='Form--field'>
          <label htmlFor='body'>Description</label>
          <input onChange={handleForm} type='text' id='body' />
        </div>
      </div>
      <button
        className='Form__button'
        disabled={formData === undefined ? true : false}
      >
        Add Post
      </button>
    </form>
  )
}
export default AddPost

This website uses cookies to enhance your browsing experience, analyze site traffic, and serve better user experiences. By continuing to use this site, you consent to our use of cookies. Learn more in our cookie policy

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policy