Quick Guide to Next.js with TypeScript — Part 1

BleatinGoat
2 min readOct 29, 2021

--

Purpose of this multi-post guide is to get you started with TypeScriptin Next.js with as less manoeuvring through documentation as possible.

In part 1, we are going to
1. Bootstrap our new Next.jsproject.
2. Configure TypeScript
3. Build a basic strictly typed view and a component

Time to spin-up a new Next.jsapp using
npx create next-app --typescript <YOUR_APP_NAME> for bare minimum views/components andtypescriptalready configured. Your installation should be complete and you should be ready to run your new Next.jsapp with yarn devexcept…

Error: > Couldn’t find a `pages` directory. Please create one under the project root

Let’s create a new directory under root named pagesand also our default page named index.tsx with code below(default page must be named index.tsx for next.js routing to pick it up as our default view). We import type NextPage to assign to our Homepage from next

Now, try running yarn dev. If you run into issue where it asks you to install typescript and @types/react. Go ahead and do that. This is to make our app understand that we are going to be writing type-safe code.

Now when you run yarn dev you will see webpackserver running your app on http://localhost:3000. One last thing to configure is to set typescript compiler option to strict by reaching inside tsconfig.json and setting strict to true.This will ensure that you have highest type-satefy enabled in your project.

Let’s create a simple but strictly typed component that shows today’s date.
Create a directory named components under root and create a file named Now.tsx and enter following code.

As you can see we are making sure that component <Now /> accepts nothing but Dateobject and therein lies the magic of TypeScript

Now, import <Now /> component in index.tsx like below.

If you see the screen below (except you should see your current date), congratulations! You have successfully set up TypeScriptwith your Next.js project.

See you in part 2.

--

--

BleatinGoat
BleatinGoat

Written by BleatinGoat

TypeScript, GraphQL, React, Next.js