TypeScript is a JavaScript superset that is supposed to securize app development by providing typing, interfaces, enums... That tiny blog was the perfect occasion to jump into typed code and to check if it really makes the app more robust.
Install TypeScript as JavaScript transpiler
iPhone 3G commercial used to claim "There's an app for that". In Gatsby' world, if you want to do something "there's a plugin for that". Therefore giving your Gatsby website the ability to parse Typescript files can be done by installing gatsby-plugin-typescript (and typescript for development)
Install it and add it into gatsby-config.js. Typescript plugin doesn't ship with type definitions so you need to add them manually. It is recommended to start with
npm install --save-dev @types/react @types/react-domNext, add tsconfig.json and tslint.json to the project root. At this point of my learning, I had no idea what it was used for. So I just copy pasted it from a gatsby starter: gatsby-starter-typescript-plus
It is now time to rename all files, components from src/**/*.js to src/**/*.tsx.
If you're importing images or packages that don't come with a module definition, you'll need to declare them by yourself. First create a .d.ts at your project root. Then declare the missing modules
// .d.ts
declare module '*.png'
declare module '*.jpg'
declare module 'react-helmet'Finally, if you're importing some components into gatsby-node to use them as page shell, don't forget to edit the path from *.js to *.tsx.
Add type-checking
Unfortunately, gatsby-plugin-typescript adds TS transpilation into JS, but it doesn't display compilation errors, which is the first reason why someone would install TS into its project. There are 2 solutions to fix that
- Add a script in your package.json :
"type-check": "tsc --noEmit",. But it needs to be manually launched, or plugged to a pre-commit/pre-push hook. I won't keep that solution - #TheresAPluginForThat: add gatsby-plugin-typescript-checker to your project. Et voilà! 💁♀️
My first open source contribution
Thanks to TS type-chcking, I was able to find an issue into TinaCMS. After investigating the documentation and some help from the TinaCMS core team, I managed to produce my 1st contribution to an open-source project. Even if it was a very small piece of code, I'm very proud of it. #100DaysofGatsby is definitely an awesome challenge ! 🏆