<?xml version="1.0" encoding="UTF-8"?><rss 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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marvin Roger on Medium]]></title>
        <description><![CDATA[Stories by Marvin Roger on Medium]]></description>
        <link>https://medium.com/@marvinroger?source=rss-359894ce813d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EYeMnRs4ea532_wXhGr0Sg.jpeg</url>
            <title>Stories by Marvin Roger on Medium</title>
            <link>https://medium.com/@marvinroger?source=rss-359894ce813d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:56:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marvinroger/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The 5 commandments of clean error handling in TypeScript]]></title>
            <link>https://medium.com/with-orus/the-5-commandments-of-clean-error-handling-in-typescript-93a9cbdf1af5?source=rss-359894ce813d------2</link>
            <guid isPermaLink="false">https://medium.com/p/93a9cbdf1af5</guid>
            <category><![CDATA[error]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Marvin Roger]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 16:26:41 GMT</pubDate>
            <atom:updated>2025-05-07T08:50:03.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDRbJFnNsiuH23Z0U9nXLg.png" /></figure><p>Dealing with errors is an essential part of software engineering.</p><p>Defining and having strong guidelines on how to handle errors will make your life easier when developing features, but also, and maybe more importantly when things go wrong!</p><p>At Orus (where we try to <a href="https://www.orus.eu/">reinvent professional insurance</a>), over time, we tailored an error strategy that works well for us and that we think could be useful to share.</p><p>While this post is mainly dedicated to error handling in TypeScript, some of the principles that we will go through are quite general and applicable to other languages as well.</p><p>Without further ado, here are our 5 error handling commandments:</p><ul><li><strong><em>#1</em>: Make sure Errors are, well… Errors</strong></li><li><strong><em>#2</em>: Don’t lose your stack trace</strong></li><li><strong><em>#3</em>: Use constant error messages</strong></li><li><strong><em>#4</em>: Provide the right amount of context</strong></li><li><strong><em>#5</em>: Don’t throw errors for problems that are expected to happen</strong></li></ul><p>Did this peak your interest? If so, <strong>read on!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*9eoWY_pN5Caen07FzQfdLA.gif" /></figure><h3>Commandment #1: Make sure Errors are, well… Errors</h3><p>In the magnificent JavaScript world, you might not be aware, but you can throw anything, not only Error instances.</p><pre>function throwNumber() {<br>  throw 123<br>}<br><br>try {<br>  throwNumber()<br>} catch (err) {<br>  console.log(err) // 123<br>}</pre><p>Although this is fun and allows some clever use cases (for example, the upcoming <a href="https://17.reactjs.org/docs/concurrent-mode-suspense.html">React Suspenses</a> is built on the fact that we can throw promises), this is not a good idea! Indeed, there are a few issues:</p><ul><li>There is no stack trace attached, so the thrown “error” loses much of its usefulness</li><li>On the caller side, almost always, actual Error instances are expected. It’s not unusual to see naive usage of err.message in the wild without checking the type of err first</li></ul><p>To ensure you’re bulletproof to this matter, first and foremost, always throw Errors in your codebase. Having this rule in mind is great but enforcing it with an ESLint rule (<a href="https://typescript-eslint.io/rules/no-throw-literal/">https://typescript-eslint.io/rules/no-throw-literal/</a> for example) is even better!</p><p>More importantly: before using a caught error, make sure it’s actually an Error. To do this, make sure you’ve enabled the useUnknownInCatchVariables flag in your tsconfig.json (note that it’s enabled by default if you’re in strict mode). This will make the error variable in a catch block unknown instead of any.</p><pre>try {<br>  runFragileOperation()<br>} catch (err) { // err is `unknown`<br>  console.log(err.message) // this will fail because we&#39;re not checking the `err` type<br>}</pre><p>This is a great step forward: we cannot misuse an error without ensuring its type first. Out of the box, it’s not practical to use though:</p><pre>try {<br>  runFragileOperation()<br>} catch (err) {<br>  if (err instanceof Error) console.log(err.message)<br><br>  // what do you do if err is not an `Error`?<br>}</pre><p>Constantly having to check the type of an error with an if block in a catch block is cumbersome. Moreover, what do you do if it’s not an Error?</p><p>The solution we’ve come up with in the Orus team is to have an ensureError function that makes sure an error is an Error. If it’s not, the thrown value is wrapped in an Error. The implementation looks like this:</p><pre>function ensureError(value: unknown): Error {<br>  if (value instanceof Error) return value<br><br>  let stringified = &#39;[Unable to stringify the thrown value]&#39;<br>  try {<br>    stringified = JSON.stringify(value)<br>  } catch {}<br><br>  const error = new Error(`This value was thrown as is, not through an Error: ${stringified}`)<br>  return error<br>}</pre><p>Armed with this function, manipulating caught errors is more straightforward:</p><pre>try {<br>  runFragileOperation()<br>} catch (err) {<br>  const error = ensureError(err)<br><br>  console.log(error.message)<br>}</pre><p>There are several benefits to doing this:</p><ul><li>It handles absolutely everything that might be thrown, and as long as the value is JSON-stringifiable, no information is lost</li><li>It creates an Error instance if needed, adding a stack trace as early as we possibly can. Therefore, the error can be propagated easily with the most relevant stack trace</li><li>The usage looks way cleaner: with one short line, you’re sure you’re manipulating an Error. Because this has to be used in every catch block, this is quite important</li></ul><p>This one simple function significantly simplified our error handling code.</p><h3>Commandment #2: Don’t lose your stack trace</h3><p>Can you spot the issue in this snippet?</p><pre>try {<br>  runFragileOperation()<br>} catch (err) {<br>  const error = ensureError(err)<br><br>  throw new Error(`Running fragile operation failed: ${error.message}`)<br>}</pre><p>Alright, the title gave it up quite early: we’re losing the stack trace of the initial error.</p><p>This does not seem like much, but having as much information as possible can help tremendously while debugging an issue.</p><p>While keeping the stack trace (“chaining” errors) was rather complicated in good old JavaScript, you’re in luck: starting with Node.js 16.9.0, and available in most browsers since mid-2021, the cause property allows you to attach an “original” error to an Error in a backward compatible way:</p><pre>const error1 = new Error(&quot;Network error&quot;)<br>const error2 = new Error(&quot;The update failed&quot;, { cause: error1 })<br><br>console.log(error2)<br><br>/* Prints:<br><br>Error: The update failed<br>    at REPL2:1:16<br>    at Script.runInThisContext (node:vm:129:12)<br>    ... 7 lines matching cause stack trace ...<br>    at [_line] [as _line] (node:internal/readline/interface:892:18) {<br>  [cause]: Error: Network error<br>      at REPL1:1:16<br>      at Script.runInThisContext (node:vm:129:12)<br>      at REPLServer.defaultEval (node:repl:572:29)<br>      at bound (node:domain:433:15)<br>      at REPLServer.runBound [as eval] (node:domain:444:12)<br>      at REPLServer.onLine (node:repl:902:10)<br>      at REPLServer.emit (node:events:525:35)<br>      at REPLServer.emit (node:domain:489:12)<br>      at [_onLine] [as _onLine] (node:internal/readline/interface:422:12)<br>      at [_line] [as _line] (node:internal/readline/interface:892:18)<br>*/<br></pre><p>As demonstrated, the original error is fully preserved, along with its stack trace. Note that it’s not limited to only one error, an error cause can have a cause which can have a cause which can have a cause… You get the idea!</p><p>If you’re wondering why we’re throwing a new Error instead of just re-throwing the original error, take the following example:</p><pre>try {<br>  runFragileOperation()<br>} catch (err) {<br>  const error = ensureError(err)<br><br>  if (!config.fallbackEnabled) throw error<br><br>  try {<br>    runFallback()<br>  } catch {<br>    // for the sake of this example, we discard the `runFallback`<br>    // stack trace on purpose, but in course on production we shouldn&#39;t!<br>    throw error<br>  }<br>}</pre><p>Compared to throwing new errors, we lose some benefits:</p><ul><li>The error message might be less clear. You’ll probably prefer your function to fail with a nice Calling API failed rather than a more obscure read ECONNRESET</li><li>We don’t know which throw ended up throwing. Is it the one from the fallback or the other? The resulting stack trace would look exactly the same, which would not be the case had we thrown a new error</li></ul><h3>Commandment #3: Use constant error messages</h3><p>Most monitoring and error tracking platforms analyze the error messages in order to determine if an error is frequent. Take the following example:</p><pre>try {<br>  await logRequest(requestId, { elapsedTime })<br>} catch (err) {<br>  const error = ensureError(err)<br><br>  throw new Error(`Could not log request with ID &quot;${requestId}&quot;`, { cause: error })<br>}</pre><p>Imagine that logRequest logs the request in a database, and the database fails. If 1 000 requests fail due to this, there will be 1 000 different error messages:</p><pre>Could not log request with ID &quot;9r7S8_ZoobNwRKafaVeP7&quot;<br>Could not log request with ID &quot;v2zGvKj-JVdFg_vjJyUP1&quot;<br>Could not log request with ID &quot;CaU_eS8olPcbbxfIPiUWN&quot;<br>[...]</pre><p>This would be problematic, because:</p><ul><li>If you’re a small company, your monitoring platform will probably alert you whenever there’s a single unexpected error. You’ll end up with 1 000 alerts</li><li>If you’re a bigger company, and your monitoring platform alerts you when a certain occurrence threshold is met, each error message being unique, you’ll never be notified</li></ul><p>The solution to this is to make sure your error messages are constant. The variable data should be set as part of the error context (or metadata or any other name you prefer). For type-safety concerns, you’ll want to create your own subclass of Error:</p><pre>type Jsonable = string | number | boolean | null | undefined | readonly Jsonable[] | { readonly [key: string]: Jsonable } | { toJSON(): Jsonable }<br><br>export class BaseError extends Error {<br>  public readonly context?: Jsonable<br><br>  constructor(message: string, options: { error?: Error, context?: Jsonable } = {}) {<br>    const { cause, context } = options<br><br>    super(message, { cause })<br>    this.name = this.constructor.name<br><br>    this.context = context<br>  }<br>}</pre><p>Now, you can attach context to an error, while making sure your error is serializable in JSON thanks to the Jsonable type. The above error would now look like this:</p><pre>throw new BaseError(&#39;Could not log request&#39;, { cause: error, context: { requestId } })</pre><p>Error grouping will then behave as expected, the error message always being the same! For debugging, you’ll still have access to the relevant data in context.</p><h3>Commandment #4: Provide the right amount of context</h3><p>This is a small one, but an important one nonetheless: attach the relevant data to your error context. Providing too little or too much context will make it harder for you to debug issues. Take the following example:</p><pre>try {<br>  await billCustomer(customer.id, quote.amount)<br>} catch (err) {<br>  const error = ensureError(err)<br><br>  throw new BaseError(&#39;Could not bill customer&#39;, {<br>    cause: error,<br>    context: { customer, quote }<br>  })<br>}</pre><p>There’s probably too much context here: chances are, to debug this, you’ll only need the customer.id and quote.amount. Debugging the issue, in this case, will require you to dig through the whole context, which might be huge (e.g. the quote could have a lot of information). Also, what if there are sensitive data in customer? Having your customer&#39;s personal information in your error monitoring platform is probably not something you want.</p><p>In this case, providing customerId and quoteAmount would have been enough.</p><h3>Commandment #5: Don’t throw errors for problems that are expected to happen</h3><p>Because of the nature of TypeScript, throwing errors should be considered a last resort, something that is hard or impossible to recover from.</p><p>Indeed, unlike other languages, it’s impossible in TypeScript to guarantee that thrown errors will be handled. This is due to the fact that thrown error types are not part of the function signature.</p><p>How can we guarantee that errors are handled, then? Well, errors should be part of the function signature. You can achieve this, for example, by leveraging the Result pattern, borrowed from Rust, which is simple but pretty powerful:</p><pre>type Result&lt;T, E extends BaseError = BaseError&gt; = { success: true, result: T } | { success: false, error: E }</pre><p>With this type, you can now express the fact that a function can fail. For example, a function reaching out to an API server would look like this:</p><pre>type ApiResponse = { data: string }<br><br>export async function fetchDataFromApi(): Result&lt;ApiResponse&gt; {<br>  try {<br>    const result = await fetch(&#39;https://api.local&#39;)<br><br>    // for the sake of this snippet we don&#39;t do it<br>    // but we should validate `result` matches the expected format<br><br>    return { success: true, result}<br>  } catch (err) {<br>    const error = ensureError(err)<br>    <br>    return { success: false, error }<br>  }<br>}</pre><p>Now, it’s impossible to access the data from the API without making sure it was successful first. Also, notice that this function will never throw.</p><p>The above example is a bit rough and verbose to use, but this is simplified to the maximum for the sake of the demonstration. In practice, there are great libraries that expose nice APIs to work with Results efficiently and more elegantly, but this is outside the scope of this article.</p><p>In short, to make sure your users have the best experience possible, ask yourself the question “Will this function probably fail?”. If so, using the Result pattern is probably a good idea, as you have the guarantee that the failure case will be handled, so your users will see a nice message or an elegant fallback instead of a crash.</p><p>That’s it for this article! I hope that these tips that we’ve collected over time at Orus will be helpful to some extent to you.</p><p>Don’t hesitate to react to this article, if you have any questions or feedback, and I’ll gladly reply!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*pz6KTUZL7fz5ua7zSBJLwQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93a9cbdf1af5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/with-orus/the-5-commandments-of-clean-error-handling-in-typescript-93a9cbdf1af5">The 5 commandments of clean error handling in TypeScript</a> was originally published in <a href="https://medium.com/with-orus">With Orus</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we migrated a 300k LoC Flow codebase to TypeScript without codebase freeze — Part 1/2]]></title>
            <link>https://blog.iziwork.tech/how-we-migrated-a-300k-loc-flow-codebase-to-typescript-without-codebase-freeze-part-1-2-98c93518fff5?source=rss-359894ce813d------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c93518fff5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marvin Roger]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 12:16:05 GMT</pubDate>
            <atom:updated>2021-07-27T12:16:05.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>How we migrated a 300k LoC Flow codebase to TypeScript without codebase freeze — Part 1/2</h3><p>At iziwork, we had a long-standing task in our backlog: migrate our Flow codebase to TypeScript. We’re happy to report that, after months of preparation, we’ve successfully migrated our 300k LoC core to TypeScript without freezing the codebase!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlAAxBH6Oq-mtjtOxkaGFQ.png" /></figure><p>In this blog post, we’re going to see what we’ve done to make this migration possible. This is the first part of a 2-part series.</p><h4>Leaving Flow</h4><p>When iziwork started, we wanted to benefit from type checking tools. We picked Flow. Fast forward, 3 years later, I think it’s safe to say that Flow lost its momentum. Even Facebook, which is behind Flow, made the switch to TypeScript. TypeScript is now widely used across the industry, the types ecosystem is way richer, and the tooling around TypeScript has evolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GeY_5W9E86L1YVMr" /><figcaption>Downloads of Flow vs TypeScript</figcaption></figure><p>Moreover, most of our projects at iziwork were already using TypeScript. It was time for our core to be migrated to TypeScript.</p><h4>Objectives</h4><p>A migration is a heavy task, and we had clear goals defined:</p><ul><li>Migrate as fast as possible, without compromising on quality</li><li>Be sure that there won’t be any potential breaking changes in the code, by working as much as possible on the type level. Therefore, the actual, compiled, runtime code would stay the same</li><li>iziwork is fast-paced, we didn’t want to freeze the codebase. The migration should be made in parallel</li><li>Automate what’s automatable, avoiding manual work as much as possible (e.g. jscodeshift)</li></ul><p>These were the objectives that fit our situation at the time. The rest of this blog post explains the things we’ve done to stay in line with these objectives.</p><h4>Incremental migration VS big bang migration</h4><p>There are two migration paths possible:</p><p><strong>1. Migrate incrementally from Flow to TypeScript</strong>, by having the two types of files in the code. This can work by leveraging the power of Babel 7 overrides</p><ul><li>It is easy to review</li><li>The migration process can easily be done in parallel and take weeks/months without having to freeze the code</li><li>Reusing types is difficult. We cannot import a Flow type in TS, and vice-versa</li><li>The IDE dev experience is terrible. Two tools to run to type-check the code, way too much information in the contextual menus, etc.</li></ul><p><strong>2. Migrate all the code in one pass</strong></p><ul><li>The review can be pretty complicated</li><li>It is tricky to do without freezing the codebase (spoiler alert — it’s doable)</li><li>The dev experience is pretty nice, the IDE only has to handle TypeScript</li><li>We can completely get rid of the Flow tooling</li></ul><p>Based on the feedback we can find on the Internet, everyone tends to agree that the second path is preferable. The fact that the review is complicated can be mitigated by having a clear process to follow, and by automating most of the process. Therefore, we’ve chosen the second path: migrate 100% of the codebase, in one pass.</p><h4>Ensuring a consistent code style</h4><p>To ensure a smooth migration, we want, as we migrate the code, to have clean diffs. This will ease the review of the different commits.</p><p>Also, we’ll run automatic migration tools, scripts, and we’ll do quite a lot of bulk find and replace. Oftentimes, these will mess up our code style, and will eventually pollute our Git history.</p><p>For this reason, it’s important to use a tool that formats your code in a deterministic way. We’ve chosen Prettier, which is pretty much the leading code format tool in the JS ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*l27xoSKQKOs9W-rC" /><figcaption>Prettier logo</figcaption></figure><p>You can choose the tool you want, but just make sure that your Flow code is “style-compliant” before starting the migration.</p><h4>Implementing a safety net</h4><p>Through the migration, we’ll go through a lot of code changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4g76dRueR4YcOTtA" /><figcaption>Diff of the final PR</figcaption></figure><p>For this reason, we need a safety net. A way for us to check that, even if we change a lot of code, we don’t break anything. In a perfect world, this is ensured by the test suite. We do have a test suite, but there are for sure paths of code that are not tested.</p><p>As stated in our objectives, we’ll work as much as possible on the type level. Therefore, ideally, the compiled JS code, stripped from all TypeScript annotations, should remain the same as the Flow one. With that in mind, we had the idea of snapshotting the compiled JS code of our Flow codebase. That way, as we migrate the code to TypeScript, we can snapshot the compiled code, compare it with our point of reference (the Flow snapshot), and ensure that we don’t break anything.</p><p>To <strong>do that, we must use the same build tool.</strong></p><p>Otherwise, the emitted code will be a bit different, and this will be tricky to review on thousand of files. Chances are that you are using Babel with the @babel/plugin-transform-flow-strip-types plugin. Luckily for us, Babel supports both Flow and TypeScript. This means that we’ll be able to use Babel as our TypeScript build tool, and not the TypeScript compiler. We’ll use tsc with its --noEmit option, to do only type-checking.</p><blockquote>⚠️ If you are not using Babel to transpile your Flow code (for example, maybe you use flow-remove-types), you should and can easily migrate to Babel.</blockquote><p>Jest has a great feature that allows us to do exactly what we want: snapshot the code and compare it with the reference snapshot. Here is the Jest test we’ve created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a6c43ec2132aae742dcd84f8215b536/href">https://medium.com/media/4a6c43ec2132aae742dcd84f8215b536/href</a></iframe><p>The above tests check two things:</p><ol><li>The file structure of the compiled code should remain the same, by storing the result of the glob function</li><li>The content of each file should remain the same</li></ol><p>Armed with this test, you’ll now want to build your code and run the test, to snapshot the file structure and the content of each file. This will generate a big .snap file, that will be the reference snapshot used by Jest.</p><blockquote>💡 Tip: Set comments: false in your .babelrc before you snapshot your code.</blockquote><blockquote>The Flow Babel plugin might format the comments in your code differently than the TypeScript plugin. Disabling comments will help you review real code changes, instead of superfluous different comments formats.</blockquote><blockquote>⚠️ Now that our snapshot is done, don’t rebase your migration branch onto your develop branch. This would break the snapshot. You&#39;ll be able to pick up the changes from develop later when you&#39;ve migrated the whole code in the migration branch.</blockquote><p>Now, every time you’ll change the code as part of the migration, you’ll run through this process:</p><ol><li>Build the code using Babel</li><li>Run the Jest safety net test</li></ol><p>If it passes, fine, the runtime code was not changed.<br>If it does not, you’ll be able to review the diff. If you are fine with the changes, you can run jest --updateSnapshot to update the snapshots</p><p>As stated previously, most of the time, you’ll work on the type level. But there are times where you’ll have or want to change runtime. For example, thanks to the strictness of TypeScript, you’ll probably spot a few bugs that Flow did not catch.</p><h4>Running automatic Flow to TS conversion</h4><p>The initial work of converting the code to TypeScript, and mapping a few built-in Flow types to built-in TypeScript types (e.g. $Keys&lt;T&gt; to keyof T), can be done automatically. There are multiple tools that are able to do this, notably:</p><ul><li><a href="https://github.com/Khan/flow-to-ts">Khan/flow-to-ts</a></li><li><a href="https://github.com/zxbodya/flowts">zxbodya/flowts</a></li></ul><p>The former is more “known”, but it crashed without any logs when ran on our code.</p><p>The latter is less known, but offers more security:</p><ul><li>It has more automatic type mappings</li><li>It automatically runs Prettier on the resulting TypeScript code</li><li>It checks that the resulting JS AST is exactly the same before and after, showing clear, detailed warnings if this is not the case</li></ul><p>Therefore, we decided to go with flowts. You can try both of these tools, your mileage may vary.</p><p>You can now run npx flowts .. Your code will now be converted to TypeScript. You might see a few warnings, and potentially some <em>error: verification failed, diff after stripping type annotations</em>. Just check the diff and fix the problems if there are any. In our 300k codebase, we had a single issue: a multiline template literal string had 2 superfluous spaces. It was trivial to fix!</p><p>Our code is now in TypeScript. The tool, by checking the AST, guarantees that the output code is the same, and the diff after stripping type annotations is the same, meaning the compiled .js is exactly the same. In other words, our code is runnable as before.</p><h4>Setting up the tooling to support TypeScript</h4><p>Our code is now written in TypeScript! It’s time to set up our tooling to support it.</p><p>Tweaking .babelrc to support TypeScript is pretty straightforward, and is only a matter of adding the @babel/preset-typescript preset. Also, we need to update the Babel CLI calls to support the .ts extension.</p><blockquote>💡 Tip: Set onlyRemoveTypeImports: true in the options of the @babel/preset-typescript preset.</blockquote><blockquote>The Flow Babel plugin removes only import type imports from the emitted code. The TypeScript plugin is a bit smarter: it also removes all imports that are only used as a type, even if not explicitly imported with the import type syntax. To ease the review of your snapshots, disabling this behavior with the above option will ensure that you&#39;ll keep the same imports as before. You can of course (and should) revert to the default behavior post-migration.</blockquote><p>You also need to configure your linter and testing library to support TypeScript. If you’re using ESLint, follow the directions of the typescript-eslint README : <a href="https://github.com/typescript-eslint/typescript-eslint">https://github.com/typescript-eslint/typescript-eslint</a></p><p>One of the most important bits of configuration is the tsconfig.json file. Because we use Babel as a build tool, you will want to configure TypeScript to only do type-checking. Here&#39;s, for instance, the configuration we&#39;re using for our backend at iziwork:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63a9244335f3d98bb839539d2835d77b/href">https://medium.com/media/63a9244335f3d98bb839539d2835d77b/href</a></iframe><p>Notice that we did not enable any strict flags. Strict flags can easily double the amount of migration time necessary to make tsc pass. We suggest enabling strict flags post-migration, incrementally.</p><p>With all the tooling set up, don’t forget to update your scripts (package.json, CI pipelines) to run tsc instead of flow check. Also, don&#39;t forget to set up your IDE for TypeScript.</p><p>Also, you can build your code with Babel, and run the Jest safety net test. You’ll notice that, as guaranteed by flowts, the transpiled code of our TypeScript version is exactly the same as the transpiled code of the initial Flow code.</p><p>By now, your unit tests and CI should pass, except for the tsc check. Success! Your codebase and tooling are now TypeScript-enabled! 🎉</p><p>There&#39;s still a long way to go, though...</p><h4>Running tsc without running away</h4><p>When you’ll run tsc, you&#39;ll probably have a lot of errors. We know how it feels: we had 20 000 errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*Szq34jUNJDDYarL6" /></figure><p>TypeScript is smarter and more strict than Flow on a lot of aspects. But don’t get discouraged, a lot of this initial flow of errors are very easy to fix:</p><ul><li>You probably have a lot of missing @types/ packages</li><li>Maybe you have some aliases in your code that are not present in the tsconfig.json</li><li>Some syntaxes are allowed in Flow, but not in TypeScript. For example, TypeScript has a TS1095: A &#39;set&#39; accessor cannot have a return type annotation error, while this is allowed in Flow (with a return type of void). These types of error are trivial to fix and can be fixed with codemods, more on that later</li></ul><p>Although a lot of these errors are trivial to fix, it’s hard to see which ones exactly when you look at the cryptic tsc output. Let&#39;s fix that!</p><h4>Getting more comprehensive error reports from tsc</h4><p>To get a better overview of the errors reported by TypeScript, it’s important to be able to synthesize the report. TypeScript does not provide such an option, but you can easily write a script yourself to handle this. Here’s how our custom report looks like (screenshot taken by the end of our migration — we had way more errors at the beginning):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*OvANVoWy6JoLYfD4" /><figcaption>Synthesized tsc report</figcaption></figure><p>This report shows two important data:</p><ol><li>The aggregated TS error types. This will allow you to have a glance at the situation, and you’ll be able to take a look at the TS documentation and determine if some errors are hard to fix</li><li>The number of errors per file, that will allow you to see which files are the most problematic. This will help you to prioritize the migration work, and to split the tasks between multiple developers</li></ol><p>The quick and dirty script we wrote to generate the above report is <a href="https://gist.github.com/marvinroger/32099aec9e222d25664f8ae87b664e97">available as a Gist, here</a>.</p><p>Armed with that, you can start analyzing all of your errors. You’ll probably see errors that can be fixed automatically…</p><h4>Applying codemods</h4><p>When we analyzed our own errors, we found a lot of these:</p><pre>const foo = {}<br>foo.bar = true // TS2339: Property &#39;bar&#39; does not exist on type &#39;{}&#39;</pre><p>The above code is perfectly valid in Flow, but it is not in TypeScript because of excess property checking. Now, if we had only a few of these errors, we could fix them manually, but we had several thousands of them. To align with the behavior of Flow, we would have to declare foo as any. There must be a way to automate this, right?</p><p>There are indeed multiple tools capable to achieve this. The one we’ve chosen is:</p><ul><li><a href="https://github.com/facebook/jscodeshift">facebook/jscodeshift</a></li></ul><p>jscodeshift is a toolkit that allows us to build codemods. A codemod is just a script that takes an AST as input that you can edit. Then, jscodeshift writes the resulting code back to the initial file. It’s a lot more powerful than regex find/replace.</p><p>Here’s the codemod that fixes the above issue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c5d7c3c365900ebf71a9fbd578b6e2b/href">https://medium.com/media/5c5d7c3c365900ebf71a9fbd578b6e2b/href</a></iframe><p>You can run it with npx jscodeshift --parser ts --extensions ts -t ./codemod.js src.</p><p>To explain it briefly:</p><ul><li>It finds all variable declarators in the AST</li><li>For each of them, if it does not already have a type annotation, if the value is an object expression and if that object does not have any properties, we mark the type annotation as any</li></ul><p>We suggest using <a href="https://astexplorer.net/">https://astexplorer.net</a>, it really helps to write codemods.</p><p>Write codemods only if you notice errors that are systematically fixed in the same way, and which would be too long to fix manually. It does not make sense to write a codemod if it takes longer to write than just fixing the issue manually.</p><p>Hopefully, you’ll be down to a few hundred or thousand errors left. When you think you’re done with the codemods, it’s time to fix the remaining errors by hand!</p><h4>Fixing the remaining errors manually</h4><p>Let’s face it, this is the most boring step of the migration, but the most rewarding one, as by the end you’ll see tsc pass.</p><p>By now, you should have a precise idea of what are the remaining errors. Looking at your custom tsc report, you should dress a list of errors to tackle first. Having 2000 errors left does not mean that you&#39;ll have to fix errors in 2000 places; by fixing an error somewhere, you might fix 100 errors elsewhere. This is why it&#39;s important to have a clear action plan.</p><p>From now on, it makes sense to not be the only one to work on the migration, as you can start migrating things concurrently.</p><p>At one point, you’ll find that all the errors left are unrelated and cannot really be prioritized anymore. If you are 2 devs working on the migration, one dev could be fixing errors starting from the top of the file list, while the other could be fixing errors from the bottom. That way, you’ll work efficiently while ensuring that you won’t overlap with your colleagues.</p><p>For reference, at iziwork, this step took us 2 days to finish for 2 developers, with about 2000 errors to fix manually.</p><p>All good, you now have a working TypeScript branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*h1j1CSXbtj-QiDI4" /></figure><p>You’re not done yet! In the next part, we’ll see how to make your TypeScript branch up-to-date with develop, which has probably evolved since the beginning of the migration, and how to migrate all the parallel branches your coworkers have been working on, before finally merging all the TypeScript code.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c93518fff5" width="1" height="1" alt=""><hr><p><a href="https://blog.iziwork.tech/how-we-migrated-a-300k-loc-flow-codebase-to-typescript-without-codebase-freeze-part-1-2-98c93518fff5">How we migrated a 300k LoC Flow codebase to TypeScript without codebase freeze — Part 1/2</a> was originally published in <a href="https://blog.iziwork.tech/">Iziwork Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>