Typescript on Nextjs 9.0
03 December 2019Nextjs 9.0 came out months ago with Typescript support and you want to try it. Don't you know where to start? Stay with me.
The overview is:
- Update Nextjs
- Create a tsconfig.json on root
- Start the server
- Rename your files
Ok, let's start.
1 - Update Nextjs
npm i next@latest react@latest react-dom@latest
If you were on version < 8, be aware of breaking changes. If you have one of the following cases, check the upgrade guide:
- Custom _app.js
- Use @zeit/next-typescript
- Export config from page
- Use withAmp
- Use pages/api/
- Use next/dynamic
Once you were done with the upgrade and fixed the breaking changes, you can go to the next step.
2 - Create a tsconfig.json on root
Go to the root of your nextjs project and create an empty tsconfig.json file.
touch tsconfig.json
3 - Start the server
npm run dev
On this point, Nextjs will configure your tsconfig.json file with default values and realize that you don't have some packages installed.
It looks like you're trying to use TypeScript but do not have the required package(s) installed
npm install --save-dev typescript @types/react
4 - Time to Typescript
Just rename your .js files to .tsx or .ts files and you're good to go.
If you don't know Typescript, I strongly recommend the main handbook https://www.typescriptlang.org/docs/handbook/basic-types.html