DEV Community

Cover image for Run a TypeScript type check in your pre-commit hook using lint-staged + husky

Run a TypeScript type check in your pre-commit hook using lint-staged + husky

Sam Jones on July 30, 2021

A great way to prevent TypeScript compilation errors from bringing down your CI pipelines is to introduce a type check before you commit your .ts f...
Collapse
 
fatedx profile image
Stephen Baker • Edited

@martinsjastad, I read your article a few months ago and was all hyped on tsc-files. I set it up and used it in Production until today when I came to the hard conclusion that it simply does not help identify errors in other files.

So, for example, if you change the way an export works in FileA and commit your code, any files importing FileA will likely all be broken, and you will not be notified of the breakage until you deploy it.

It is for this reason that I instead added a Husky pre-commit hook to my project that executes npx tsc on commit and fails the commit if any errors are found.

I hope this helps someone. :)

Collapse
 
thiagocolebrusco profile image
thiagocolebrusco

I was looking for something like lint-staged but then I thought exactly the same thing. It is not helpful for validating TS.

Collapse
 
skathuria29 profile image
Saloni Kathuria

Hello @fatedx so by this, your pre commit hook runs on all files be it staged or unstaged ? In order to catch that import error.

Collapse
 
luckydevboy profile image
Mohammad Reza Ghasemi

Can you explain how did you do that?

Collapse
 
mrms profile image
Martin Sjåstad

Would this check the types of other files affected by changes to the staged files?

Collapse
 
samueldjones profile image
Sam Jones

Hmm I don't think it would as it specifically looks at staged - worth investigating though!

Collapse
 
amiceli profile image
amiceli

@samueldjones you made my day !
I added it to lint-staged config (custom d.ts file for import with files like .vue ;) ) and it works !
Really thanks you.

Collapse
 
omigtito profile image
Miguel Machado Pacheco

Thanks! Exactly what i was looking for!

Collapse
 
thomassalty profile image
Thomas Soos

What if there are let's say 10 staged *.ts files and all of them have type errors? Will this solution type check all 10 files or throws an error after the first one and skips the rest?

Collapse
 
nanacti profile image
Nana-Cti

My solution

 "lint-staged": {
    "**/*.ts": "bash -c \"tsc $* --noEmit\""
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zarela_graves_f627f944011 profile image
Zarela Graves

This works, but only if your codebase is small. I tried implementing this with Husky and lint-staged and made VS Code super slow.