<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[TypeScript - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/typescript/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>TypeScript - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/typescript/</link></image>
<lastBuildDate>Sun, 27 Nov 2022 15:46:55 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/typescript/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[How to incrementally migrate a Gatsby app to TypeScript]]></title>
<description><![CDATA[Learn how you can safely adopt TypeScript in your project, right now, without major changes.]]></description>
<link>https://rafaelquintanilha.com/how-to-incrementally-migrate-a-gatsby-app-to-typescript/</link>
<guid isPermaLink="false">6383829114168e003dd8f5b1</guid>
<category><![CDATA[React]]></category><category><![CDATA[Gatsby]]></category><category><![CDATA[TypeScript]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 27 Jul 2022 15:43:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Tips on how to migrate a Gatsby app to TypeScript" loading="lazy" decoding="async" width="730" height="487" src="https://rafaelquintanilha.com/_astro/how-to-incrementally-migrate-gatsby-app-typescript--1--1.CSmy53RC_27UfQz.webp"><figcaption>Tips on how to migrate a Gatsby app to TypeScript</figcaption></figure>
<p>It shouldn’t come as a surprise that TypeScript is getting more traction among developers by the day. Support for it has grown considerably, as well as the community and number of projects adopting this technology.</p>
<p>It wasn’t always like that, though. Web developers have been burned before by hot technologies that disappeared, and it’s only fair that some in the community are more skeptical about big changes. In fact, <a href="https://en.wikipedia.org/wiki/Lindy_effect" rel="noopener noreferrer" target="_blank">the Lindy effect</a> proposes that every day a piece of technology continues to survive, the longer it is expected to exist.</p>
<p>The goal of this article is not to convince you to migrate to TypeScript; I assume that if you are here, you have already been sold on the benefits of static typing in a dynamic language like JavaScript. However, if you are like me, you probably have been delaying the migration, fearful of the amount of work needed to set it in motion.</p>
<p>Well, fear no more! I’ve done the heavy lifting for you. In this article, you will learn how to adopt TypeScript incrementally, so you can have a smooth transition and a good night of sleep after work.</p>
<h2 id="why-incrementally"><strong>Why incrementally?</strong></h2>
<p>Why do we have “incrementally” in the title of this article? Isn’t that just delaying the inevitable? Why not perform a full migration at once?</p>
<p>Those are valid points, and in some cases, they can even be the most advisable. However, I am assuming you have a somewhat large project, big enough that using a codemod won’t work (or will require too much workaround).</p>
<p>Or maybe you work on a specific part of an app in a larger team and want to run a pilot before doing the big change.</p>
<p>In all cases, there are valid scenarios where one would take the cautionary road first. And even though you will find a bunch of codemods or migration methods that claim to be seamless, the reality is that if your project has some complexity, it might not be as easy as they preach.</p>
<p>However, to offer a counterpoint, the folks at Stripe seem to disagree with me. They just recently published a <a href="https://stripe.com/blog/migrating-to-typescript" rel="noopener noreferrer" target="_blank">piece claiming to have migrated millions of lines of code to TypeScript.</a> If you are feeling adventurous, it’s worth checking it out!</p>
<h2 id="how-to-set-up-typescript-in-an-existing-gatsby-app"><strong>How to set up TypeScript in an existing Gatsby app</strong></h2>
<p>Alright, for today’s experiment we’ll assume you already have a Gatsby app and want to perform a gradual migration.</p>
<p>Remember that if you are creating a new project today, Gatsby already supports TypeScript as the main language from the beginning. Unfortunately, that’s not the case for most projects that were bootstrapped in older versions of Gatsby, so we are going to take a different route.</p>
<p>The Gatsby docs already present a <a href="https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/#migrating-to-typescript" rel="noopener noreferrer" target="_blank">good guide on how to migrate</a>. However, there are a few tweaks that we need to do in order to get it up and running smoothly.</p>
<h3 id="change-your-js-files-to-tsx"><strong>Change your .js files to .tsx</strong></h3>
<p>The easier part is to change all components you want to migrate to .tsx, or create new ones in this format. No work is needed on Gatsby’s side for this to work! That’s pretty neat.</p>
<h3 id="install-dependencies"><strong>Install dependencies</strong></h3>
<p>There are, however, some libraries to be installed. Make sure you add them to your <code>devDependencies</code>:</p>
<figure class="code"><figcaption>shell</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="shell"><code><span class="line"><span style="color:#EDCC95">$</span><span style="color:#97CCAE"> npm</span><span style="color:#97CCAE"> i</span><span style="color:#97CCAE"> –save-dev</span><span style="color:#97CCAE"> @types/node</span><span style="color:#97CCAE"> @types/react</span><span style="color:#97CCAE"> @types/react-dom</span><span style="color:#97CCAE"> typescript</span></span></code></pre></figure>
<h3 id="generate-tsconfig"><strong>Generate</strong> <strong><code>.tsconfig</code></strong></h3>
<p>TypeScript has a config file called <code>.tsconfig</code>, which is hugely customizable and will vary from project to project. However, there are some specific changes we need to make in order to allow TypeScript and JavaScript to coexist in harmony, as this is a requirement for everyone to adopt TS gradually.</p>
<p>An example of a working <code>.tsconfig</code> is as follows. Make sure to add it to the root folder of your project:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#ECEBE8">{</span></span>
<span class="line"><span style="color:#97CCAE">  "compilerOptions"</span><span style="color:#ECEBE8">: {</span></span>
<span class="line"><span style="color:#97CCAE">    "target"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"es2016"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "jsx"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"react"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "module"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"commonjs"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "allowJs"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "outDir"</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">"./dist"</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "esModuleInterop"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "forceConsistentCasingInFileNames"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "strict"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#97CCAE">    "skipLibCheck"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">true</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#97CCAE">  "exclude"</span><span style="color:#ECEBE8">: [</span><span style="color:#97CCAE">"node_modules"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">"public"</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">".cache"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>You can also check an example <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/tsconfig.json" rel="noopener noreferrer" target="_blank">on this public repo in GitHub</a>.</p>
<p>Some of the needed configs are as follows:</p>
<ul>
<li>Add <code>"jsx": "react" </code>to make sure the compiler knows we are in a React project</li>
<li>Set <code>allowJs: true</code>; once JavaScript and TypeScript need to coexist, this flag should be turned on</li>
<li>Add <code>outDir: "./dist"</code>, which makes VS Code happy and prevents unwanted errors</li>
</ul>
<h3 id="declaring-globals"><strong>Declaring globals</strong></h3>
<p>If you got this far, you already have most of your setup working. However, there are still some rough edges.</p>
<p>The most obvious is about CSS modules; Gatsby works with CSS modules by default and we need to let TypeScript be happy about it. If you use <a href="https://blog.logrocket.com/how-to-use-svgs-in-react/" rel="noopener noreferrer" target="_blank">SVGs as components as described here</a>, this will also be useful.</p>
<p>At the <code>src</code> folder of your project, create a file called <code>globals.d.ts</code> and add the following:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.module.css"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.module.scss"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">declare</span><span style="color:#A1C1E4"> module</span><span style="color:#97CCAE"> "*.svg"</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> content</span><span style="color:#A1C1E4">:</span><span style="color:#A1C1E4"> string</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> content;</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This will make sure that both CSS and SVG are <a href="https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html" rel="noopener noreferrer" target="_blank">treated and handled as modules</a>.</p>
<p>Again, you can check <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/src/globals.d.ts" rel="noopener noreferrer" target="_blank">a working example in GitHub</a>.</p>
<blockquote>
<p>If you are using ESLint, it may complain about .d.ts files. In this case, you can <a href="https://stackoverflow.com/questions/63238879/eslint-only-declares-and-type-imports-are-allowed-inside-declare-module/63239805#63239805" rel="noopener noreferrer" target="_blank">disable the linter in such extensions</a>.</p>
</blockquote>
<h2 id="typing-using-prop-types"><strong>Typing using prop types</strong></h2>
<p>One of the main advantages of TypeScript is to allow static typing in JavaScript. When developing with React, this is much welcomed, because it makes it harder for us to add non-existing props or even pass the wrong variable.</p>
<p>Before TypeScript was a thing, the React team popularized <a href="https://reactjs.org/docs/typechecking-with-proptypes.html" rel="noopener noreferrer" target="_blank">typechecking with prop types</a>.</p>
<p>Prop types were an intermediary step between no validation and strict typing. With prop types, developers could list all props in a given component, their corresponding type, and whether they are optional or mandatory.</p>
<p>For example, suppose we have a component that receives a prop called <code>magicNumber</code>, which of course should have the type number:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PropTypes </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'prop-types'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … } </span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">MyComponent.propTypes </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber: PropTypes.number.isRequired</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Suppose then that we render <code>MyComponent</code> but forget to pass <code>magicNumber</code> as prop, or pass a string instead. We would see a warning like this in the console, when in dev mode:</p>
<figure class="image"><img alt="Warning in dev mode" loading="lazy" decoding="async" width="768" height="68" src="https://rafaelquintanilha.com/_astro/warning-in-dev-mode.CFyX5tVT_2ajXlX.webp"><figcaption>Warning in dev mode</figcaption></figure>
<p>However, there would be no static validation, and it’s easy to overlook this kind of error in bigger components or larger projects. Also, we can add a prop but forget to set its type (there are some linters that help you with that though).</p>
<p>Using static typing, you can deprecate prop types in favor of regular TypeScript types:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">type</span><span style="color:#EDCC95"> Props</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber</span><span style="color:#A1C1E4">:</span><span style="color:#A1C1E4"> number</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }</span><span style="color:#A1C1E4">:</span><span style="color:#EDCC95"> Props</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … }</span></span></code></pre></figure>
<p>Now, if you have a .tsx component that renders <code>MyComponent</code>, passing a prop with the wrong type will raise an error at build time:</p>
<figure class="image"><img alt="Build time error" loading="lazy" decoding="async" width="730" height="208" src="https://rafaelquintanilha.com/_astro/build-time-error--1-.BK12cyVy_Hg3NI.webp"><figcaption>Build time error</figcaption></figure>
<p>And that’s it! Safer, but less verbose, and comes with all typing benefits. All in all, prop types work but are less powerful than a robust typing strategy like TypeScript. If you want to get deeper on this subject, I recommend you read our preview article on the subject: <a href="https://blog.logrocket.com/comparing-typescript-and-proptypes-in-react-applications/" rel="noopener noreferrer" target="_blank">Comparing TypeScript and PropTypes in React applications</a>.</p>
<p>If you are convinced that static typing is superior to prop types, you should also know that there’s a caveat when ditching prop types in a project that is a hybrid of TypeScript and JavaScript.</p>
<p>Suppose that we have a <code>WithTypeScript.tsx</code> component that renders the TypeScript version of <code>MyComponent</code>. If we try to pass <code>magicNumber="Hello World"</code> this is going to raise an error once there’s a type mismatch, as seen above.</p>
<p>However, if <code>WithTypeScript.tsx</code> receives <code>magicNumber</code> from a parent component written in pure JavaScript and passes it along to <code>MyComponent.tsx</code>, there is no way to validate if the variable is indeed a number. Once the parent component has no typing, no static error will be raised. And because there are no prop types in <code>MyComponent.tsx</code>, no runtime error will be raised. As such, this type mismatch won’t be raised anywhere.</p>
<figure class="image"><img alt="No runtime error" loading="lazy" decoding="async" width="730" height="282" src="https://rafaelquintanilha.com/_astro/no-runtime-error--1-.y26EYQZ8_Z1h5bGI.webp"><figcaption>No runtime error</figcaption></figure>
<p>Note how <code>IndexPage.js</code> calls a TypeScript component <code>WithTypeScript.tsx</code> with a wrong prop type. No warning is seen either in the editor or in the browser console.</p>
<p>Bear in mind that this only happens when .js and .tsx components are communicating, which will inevitably happen if you are gradually adopting TypeScript. Fortunately, there’s a solution for it: we can have the best of both worlds by inferring types from prop types in TypeScript components. This way, we retain the prop types, but automatically convert them into types using the function <code>InferProps</code> from the <a href="https://www.npmjs.com/package/prop-types" rel="noopener noreferrer" target="_blank">prop-types</a> library.</p>
<p>This would be <code>MyComponent.tsx</code> combining types and prop types:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "react"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PropTypes, { InferProps } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> "prop-types"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> Props </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  magicNumber: PropTypes.number.isRequired,</span></span>
<span class="line"><span style="color:#ECEBE8">};</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">type</span><span style="color:#EDCC95"> MyComponentTypes</span><span style="color:#A1C1E4"> =</span><span style="color:#EDCC95"> InferProps</span><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">typeof</span><span style="color:#ECEBE8"> Props>;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MyComponent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ({ magicNumber }</span><span style="color:#A1C1E4">:</span><span style="color:#EDCC95"> MyComponentTypes</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { … };</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">MyComponent.propTypes </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> Props;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> MyComponent;</span></span></code></pre></figure>
<p><a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract/blob/master/src/components/ChildTypeScript.tsx" rel="noopener noreferrer" target="_blank">A full example can be seen here</a>.</p>
<p>The above solution will raise a static error at build time if there’s a type mismatch but also raise a runtime error in the browser console if the wrong type is passed from a .js to a .ts component along the way. The drawback is that your code becomes more verbose.</p>
<p>However, if newer components only communicate with other .ts files, then it should be safe to ditch prop types. Eventually, when the migration is complete, you can completely remove them.</p>
<h2 id="conclusion"><strong>Conclusion</strong></h2>
<p>TypeScript is an exceptional tooling, but some developers refrain from adopting it in an existing codebase. This article aimed to elucidate how you can do it safely in your project, right now, without major changes.</p>
<p>While Gatsby in particular supports .tsx files out of the box, you need some workarounds to make your compiler happy considering typical approaches present in Gatsby codebases. Declaring globals for CSS Modules and SVGs are common pain points.</p>
<p>Finally, by having JavaScript communicating with TypeScript, we can’t guarantee that some typing errors won’t be opaque. Because of that, we can leverage the prop-types library and infer the types, getting the best of both worlds until we are safe to deprecate.</p>
<p>All code and examples present in this article can be found in <a href="https://github.com/rafaelquintanilha/gatsby-ts-vanilla-extract" rel="noopener noreferrer" target="_blank">this repo on GitHub</a>. Give it a try!</p>]]></content:encoded>
</item>
</channel>
</rss>
