Use Typescript with Gatsby and make type check available

April 22, 2021

programming
article cover

Type check after all

Me personally, I love dynamic typing language much. But as the project grows and data becomes complicated I end up using type check eventually. React has PropTypes library but it’s kinda useless since it doesn’t output errors on build. It seems we only have one choice after all.

Let’s set up Typescript in Gatsby project.

Set up Typescript

There always be some helpful plugins when you want to do something in Gatsby. Here is the plugin to set up Typescript.

gatsby-plugin-typescript

Install the package

npm install --save gatsby-plugin-typescript

or

yarn add gatsby-plugin-typescript

Add to gatsby-config.js

plugins: [
    `gatsby-plugin-typescript`,
]

Make tsconfig.json in root directly

{
  "include": ["./src/**/*"],
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "lib": ["dom", "es2017"],
    "allowJs": true,
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmit": true,
    "skipLibCheck": true,
    "moduleResolution": "node"
  }
}

Done!?

Unfortunately, Nope. It’s not doing type check. Let’s see the description of the plugin closely again.

Allows Gatsby to build TypeScript and TSX files. Does NOT run type checking during build (see Caveats).

Alright…, but who on earth is using Typescript without type check?

Solution

I found a very nice plugin to solve this problem. As I said, There always be some helpful plugins when you want to do something. Can’t thank enough.

gatsby-plugin-typescript-checker

Add this plugin for gatsby-plugin-typescript

Install

npm install --save gatsby-plugin-typescript-checker

or

yarn add gatsby-plugin-typescript-checker

Add to gatsby-config.js

plugins: [
    `gatsby-plugin-typescript`,
    `gatsby-plugin-typescript-checker`, // new
]

Install @types

npm install --save-dev typescript @types/node @types/react @types/react-dom @types/react-helmet @types/styled-components

or

yarn add -D typescript @types/node @types/react @types/react-dom @types/react-helmet @types/styled-components

// @types/styled-components is optional

Now you can see errors on the browser console and terminal when the data type is not right!


Profile picture

Photographer / Web engineer working in Berlin.
A Japanese living with a Slovak wife and two German cats.