API Invocation in NextJS/TypeScript application deployed to Vercel

Although there could be a lot of differences between JavaScript(JS) and TypeScript(TS), a few that stand-out right away and covered in this blog post are these:


Side-by-side comparison of TS vs JS code(for same scenario):



As a continuation of my earlier blog, I decided to move my NextJS JavaScript  app to TypeScript. So, the notes are here:

Create a typescript-based NextJS app: npx create-next-app@latest --ts

npm run dev in the project folder starts the application locally:


Then, added the TS code (index.tsx below):

One line that caused me lot of issues is getting this one correct:

   let data = await res.json() as Props;  

if you compare this line to one that I have in index.js part of my earlier blog, it looks like this:

const data = await res.json();

Although the changeover to let instead of const was based on how frequently the variable will change and is common for both languages, it took me sometime to realise how strongly-typed TS is. So, that is the reason the type-cast to Props is important in typescript. 

Most importantly, the localhost:3000 didn't have any issues but only when I deployed to Vercel, I realised there are build errors and I executed npm run build locally to see errors such as this one:

Type error: Object is of type 'unknown'.


  15 |    return {

  16 |      props: {

> 17 |        fact: data.fact,

     |              ^

  18 |        length: data.length

  19 |      }

  20 |    }


So, always execute npm run build before pushing to Vercel!

When you work with TS, you must think in lines of type, interface similar to OOPS-based programming languages like C#

Also, note the use of type and the response using the concerned type for casting. You can also instead use an interface like this:

interface IProps {

    fact: string;

    length: string;

};

and, the type casting will then change as follows:

let data = await res.json() as IProps;


index.tsx

import type { NextPage } from 'next'

import fetch from 'node-fetch'


type Props = {

    fact: string;

    length: string;

};


export async function getServerSideProps() {

   let res = await fetch(

    "https://catfact.ninja/fact"

   );

   let data = await res.json() as Props;  

   return {

     props: {

       fact: data.fact,

       length: data.length

     }

   }

}


const Home: NextPage<Props> = (props) => { 

    return (      

      <div>

  <div>{props.fact}</div>   

  <div>{props.length}</div>

  </div>

    ); 

}

export default Home


Deployed to Vercel:


GitHub

Comments