Skip to content

Instantly share code, notes, and snippets.

@dsernst
Last active April 19, 2024 08:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsernst/b1d2df3bb5be777e1dcb27e5c0d2474d to your computer and use it in GitHub Desktop.
Save dsernst/b1d2df3bb5be777e1dcb27e5c0d2474d to your computer and use it in GitHub Desktop.
Run typescript compiler in pre-commit hook
// Run this script to check our files for type errors
// using our existing tsconfig.json settings
//
// Usage: node typecheck.js
//
const fs = require('fs')
const stripJsonComments = require('strip-json-comments')
const tsConfig = JSON.parse(stripJsonComments(fs.readFileSync('./tsconfig.json', 'utf8')))
const { exec } = require('child_process')
const chalk = require('chalk')
const filesToCheck = 'src/*.ts{,x}' // <--- YOU PROBABLY WANT TO CHANGE
const options = {
...tsConfig.compilerOptions,
// Overrides:
incremental: false,
}
let optionsString = ''
Object.keys(options).forEach(key => {
const value = options[key]
const option = '--' + key
const type = typeof value
if (type === 'boolean') {
if (value) {
optionsString += option + ' '
}
} else if (type === 'string') {
optionsString += option + ' ' + value + ' '
} else if (type === 'object') {
if (Array.isArray(value)) {
optionsString += option + ' ' + value.join(',') + ' '
}
} else {
console.log('\nMissing support for compilerOption:')
console.log({ [key]: { type, value } })
}
})
console.log('💅 Typechecking files...')
exec(`tsc ${filesToCheck} ${optionsString}`, (err, stdout) => {
const results = stdout
.split('\n')
// Filter out excludes
.filter(line => !tsConfig.exclude.some(exclude => line.startsWith(exclude)))
// Highlight filenames
.map(line => line.replace(/^(\w|-|\/|\.)+tsx?/, filename => chalk.bold.cyan(filename)))
// Remove empty lines
.filter(line => line)
if (err && results.length) {
console.log(results.join('\n'))
} else {
console.log('✅ Typecheck passed without errors.')
}
})
@dsernst
Copy link
Author

dsernst commented Feb 4, 2020

See microsoft/TypeScript#27379 (comment) for context:

I'm also in the camp that wants to run the compiler in a pre-commit hook.

Inspired by @mmkal's suggestion, I put together this simple node script: https://gist.github.com/dsernst/b1d2df3bb5be777e1dcb27e5c0d2474d#file-typecheck-js-L13

Example w/ error:

Screen Shot 2020-02-04 at 4 01 37 AM

Otherwise:

Screen Shot 2020-02-04 at 3 51 38 AM

Works great for my use-case. Hope others may find useful. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment