0

I'd like to incorporate a type check in my build process.

I keep my build process in a build.sh file where a call multiple CLI like:

// TYPE CHECK HERE <---
rimraf dist
webpack...
babel...

I'd like to type check my /src folder and stop my build process if it find any type errors.

How can I do that? Should I use tsc? Is there any option I need to add to make it stop in case it finds any errors?

I'm trying implement this basic functionality example:

test.sh

tsc src/testScript.ts --noEmit --skipLibCheck
echo "AFTER TSC"

I've intentionally added this error to the testScript.ts.

enter image description here

You can see that the rest of the test.sh script just keeps running. Is there a way to check if the tsc call has found any errors? Then I could check the result and stop the script at that point.

cbdeveloper
  • 14,014
  • 11
  • 57
  • 145
  • Yes, You should use `tsc`. See docs https://www.typescriptlang.org/docs/handbook/compiler-options.html. `tsc src/*.ts` – captain-yossarian Jan 06 '21 at 13:12
  • @captain-yossarian Thanks. It works as far as running the type check. But it does not stop the script from keep running after `tsc` has found errors. How could I implement this? – cbdeveloper Jan 06 '21 at 16:36

1 Answers1

1

Here is how I've implemented this:

build.sh

TYPE_ERRORS="$(tsc --project ./tsconfig.json)"

if [[ -n $TYPE_ERRORS ]]; then
  echo "FOUND ERRORS"
  echo $TYPE_ERRORS
  echo "WILL EXIT NOW"
  exit
fi

echo "NO ERRORS WERE FOUND"

The result of the tsc will be stored in $TYPE_ERRORS. If the result is not empty, it will log the errors and exit the script. Else, the script will continue and log NO ERRORS WERE FOUND.

Note: Instead of logging the errors by doing echo $TYPE_ERRORS, you can also call the tsc command again, because the log will be prettier (with colors). Like:

build.sh

TYPE_ERRORS="$(tsc --project ./tsconfig.json)"

if [[ -n $TYPE_ERRORS ]]; then
  echo "FOUND ERRORS"
  tsc --project ./tsconfig.json   # THIS WILL LOG PRETTIER LOGS
  echo "WILL EXIT NOW"
  exit
fi

echo "NO ERRORS WERE FOUND"

The log from echo $TYPE_ERRORS will be plain text only (no colors).


The code above will look in tsconfig.json to see which compiler options should be applied and also which folders must by compiled.

But you can also specify folder/file, like:

tsc src/someFile.ts --noEmit --someOtherOption

This is how I call the .sh file from an npm script:

package.json

{
  "scripts": {
    "build: "./my-bash-scripts-folder/build.sh"
  }
}

Than I run it as npm run build like always.


UPDATE: USING EXIT CODES

You can use the exit code from the tsc script to know if it has thrown any errors.

The standard is 0 for successful runs.

tsc --project ./tsconfig.json
TYPE_CHECK_EXIT_CODE=$?

if [[ $TYPE_CHECK_EXIT_CODE == "0" ]]; then
  echo "TYPE CHECK - SUCCESS"
else
  echo "TYPE CHECK - FAILED"
fi
cbdeveloper
  • 14,014
  • 11
  • 57
  • 145