How to lint for Typescript compilation issues?

吃可爱长大的小学妹 提交于 2019-11-29 13:37:24

I think your best bet is to run tsc --noEmit -p . and filter the output for errors in the modified files. For example, I saved the following script to tsc-some-files:

#!/bin/bash
declare -A include_files
for f in "$@"; do
  include_files["${f#$PWD/}"]=1
done
node_modules/.bin/tsc --noEmit -p . | (
  status=0
  show_continuation=false
  while IFS='' read -r line; do
    case "$line" in
    (' '*)
      if $show_continuation; then
        echo "$line" >&2
      fi
      ;;
    (*)
      file="${line%%(*}"
      if [ -n "${include_files["$file"]}" ]; then
        show_continuation=true
        echo "$line" >&2
        status=1
      else
        show_continuation=false
      fi
      ;;
    esac
  done
  exit $status
)

and set ./tsc-some-files as my lint-staged command, and it seemed to work. (Writing this in a programming language other than bash, if desired, is left as an exercise for the reader.)

Keep in mind though that editing one file can introduce an error in another file (e.g., if you changed the type of something that the other file is using), so I'd urge you to get your project clean of TypeScript errors ASAP by whatever hacks necessary (as long as you mark them so you can search for them later) and then set your hook to require no errors in the whole project. In fact, with respect to noImplicitAny in particular, when I migrated a JavaScript project to TypeScript several years ago, I wrote a script that inserted an explicit any everywhere there was an implicit any error, then I fixed the explicit anys at my leisure. I can share the script if you're interested.

I don't have enough reputation to add this as a comment, but anyone that is getting an error similar to

./scripts/ts-staged-files.sh: line 4: 
   src/ui/Components/Select/Select.tsx: division by 0 
  (error token is "/Components/Select/Select.tsx")

I made this small modification to Matt McCutchen's answer to fix it.

#!/bin/bash

include_files=()

for f in "$@"; do
  include_files+=("${f#$PWD/}")
done
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!