Next.js comes with a TypeScript support out of the box, but not by default (after all, not every project uses TypeScript!)
In this quick lesson we're going to learn how to enable TypeScript support in a Next.js app and how to enable strict
mode in TypeScript (since it's disabled by default in Next.js)
Tomasz Łakomy: [0:00] Next.js comes with a TypeScript support, but it is not enable by default. Luckily, we can make that happen.
[0:06] In order to start adding TypeScript to our Next.js app, go ahead and create a brand new tsconfig.json. Next, open up the terminal and run npm run dev in order to start the Next.js server. This is going to tell us that it looks like you are trying to use TypeScript, but you do not have the required packages installed. We have to install all those packages.
[0:25] Let me just copy that and paste it over here. This is going to install TypeScript and types for React and types for node. Now it's done. Let me clear the terminal and run npm run dev once again. This is going to detect that we had that tsconfig.json file and is going to populate it for us. We can see everything here.
[0:43] One important thing to notice is that the strict mode from TypeScript is disabled by default. This fact is also highlighted in the Next.js official documentation, that the strict mode is turned off by default. When you feel comfortable with TypeScript, it is recommended to turn it on.
[0:58] Luckily, TypeScript is going to complain only about the pages that we are actively working on. If you have any inactive pages that we are not touching at the moment, those pages do not block the development process.
[1:09] In order for us to write better code, I'm going to enable the strict mode. I'm also going to enable strictNullChecks. This is going to allow us to avoid the vast majority of runtime issues.
[1:20] Also bear in mind that allowJs is set to true. We can have both TypeScript and JavaScript files in this project. With everything complies, all that remains is renaming this file from index.js to index.tsx.
[1:33] We can verify that we do have TypeScript support. For instance, if I create a new variable. I'm going to call it title. It's going to be of type string, and it's going to be = Next.js + TypeScript. I'm going to use this title as the title of our page.
[1:47] Our server is still running. We can see that everything has been compiled successfully. We also can see those changes in the app.
If you use pnpm as package manager, DO NOT use pnpm for install
typescript
and@types
instead of npm or yarn, or you get warning and errors.Warning when install
typescript
and@types
I've got when I used pnpm:I've got following internal server error after install above:
more detail: previous lesson's Discuss