Automating some steps of the conversion of an existing codebase to TypeScript

Wed Sep 2, 2020
~300 Words

Below is a simple script which will take the list of .jsx files (in this case under the app/javascript directory and for each file it will rename it to have a .tsx extension, and then if webpack compiles (which means that the code type checks) and all tests pass, then this rename can be converted. If either fail, then the rename is reversed and the next file is tested.

The motivation for this is that in a codebase of some hundreds of JS(X) files, the majority can actually be renamed cleanly, in part as currently we allow the any type implicitly. By running this script we have managed to reduce a significant part of manual checking while we make a first pass at converting the codebase over to TypeScript.

Naturally once all files are building as TypeScript rather than JS files then we will start to address the various warnings (e.g. for implicit any).

The script can of course be modified to target .js files instead.

#!/usr/bin/env bash

set -uxo pipefail

find app/javascript -type f -name '*.jsx' | while read sourcePath; do
  targetPath=$(bash -c 'echo "${1%.jsx}.tsx"' bash $sourcePath)

  git mv $sourcePath $targetPath



  if [ $webpackStatus -eq 0 ]; then
    yarn test


  if [[ $webpackStatus -ne 0 || $testStatus -ne 0 ]]; then
    git reset head .
    git checkout .
    rm $targetPath
    git commit -a -m "Rename $sourcePath -> $targetPath"

Did you find this post useful? If you would like help with anything then you can contact me any time via Twitter.