Quick Guide to Next.js with TypeScript — Part 1
Purpose of this multi-post guide is to get you started with
Next.js with as less manoeuvring through documentation as possible.
In part 1, we are going to
1. Bootstrap our new
3. Build a basic strictly typed view and a component
Time to spin-up a new
npx create next-app --typescript <YOUR_APP_NAME> for bare minimum views/components and
typescriptalready configured. Your installation should be complete and you should be ready to run your new
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
NextPage to assign to our Homepage from
Now, try running
yarn dev. If you run into issue where it asks you to install
@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
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
<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
See you in part 2.