Adding TypeScript to your NextJS project
- Published on
- Authors
- Name
- Bobby Hall Jr
- @bobbyhalljr_dev
Adding TypeScript to your NextJS project super simple.
Let's get started!
Step 1: Create ts.config.json file
Create a ts.config.json
file in the root of your project.
Run this in your command line:
touch tsconfig.json
Step 2: Install TypeScript packages
Run these two commands in the command line.
Install TypeScript globally
npm install -g typescript
Install TypeScript packages.
npm install typescript @types/react @types/node
or
yarn add typescript @types/react @types/node
Step 3: Start or re-start the server
Let NextJS work it's magic.
Once you have installed all the TypeScript packages all you need to do is start or re-start the NextJS server and NextJS will populate our tsconfig.json
file for us! 😮
Run this in your command line:
npm run dev
or
yarn dev
Your tsconfig.json
file should look like this:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"rootDir": "src",
"typeRoots": ["src/types", "node_modules/@types"]
},
"include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Step 4: Switch file extensions
Now in any file you want to use TypeScript you have to switch the file extention from .js
to .ts
or .tsx
if your using TypeScript with jsx.
For example, if you have a file called index.js
you need to switch it to index.ts
or index.tsx
for use with jsx.
Step 5 (Optional): Turn on strict mode
If you are migrating a JavaScript codebase to TypeScript keep
"strict": false
In order to enjoy the full benefits of type saftey were going to set the strict
property to true
in the tsconfig.json
file.
Like so:
"strict": true,
What is strict mode?
The strict option in the TypeScript compiler turns on a set of type checking rules.
There are serveral options you can customize. Just replace the strict
property:
"strict": true
with this:
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictBindCallApply": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
Check out this great article by Andy Li that explains these options in detail. "Strict Mode" TypeScript config options
⚠️ WARNING: Do not turn on strict mode if your migrating a JavaScript codebase to TypeScript. It creates a flood of type errors. If you are migrating JavaScript to TypeScript keep
"strict": false
.