Skip to content

Instantly share code, notes, and snippets.

@zorji
Last active July 26, 2024 12:43
Show Gist options
  • Save zorji/3d33d52dcde22432c12449d49ff1d02b to your computer and use it in GitHub Desktop.
Save zorji/3d33d52dcde22432c12449d49ff1d02b to your computer and use it in GitHub Desktop.
A script to auto add // @ts-ignore to lines with TypeScript compilation error
/**
* A script to auto add // @ts-ignore to lines with TypeScript compilation error
* This could be useful when you are upgrading your tsc version, or introduced new changes in tsconfig or just converting JS codebase to TS.
* Example usage:
* $ npx tsc > compilation-errors.log
* $ npx ts-node auto-ts-ignore.ts compilation-errors.log
*/
import { readFile, writeFile } from 'fs/promises'
const errorLogFile = process.argv[2]
async function main() {
const errLineRegex = /(.+)\((\d+),\d+\): error/
const errorLog = await readFile(errorLogFile, { encoding: 'utf-8' })
const files: Record<string, number[]> = {}
for (const line of errorLog.split('\n')) {
const matched = errLineRegex.exec(line)
if (matched !== null) {
const filename = matched[1]
const lineNumber = parseInt(matched[2], 10)
files[filename] = files[filename] || []
files[filename].push(lineNumber)
}
}
for (const filename in files) {
const lineNumbers = [...new Set(files[filename])]
const fileContent = (await readFile(filename, { encoding: 'utf-8' })).split('\n')
// lineNumber is 1-based index
const affectedLineContent: string[] = lineNumbers.map(lineNumber => fileContent[lineNumber - 1])
lineNumbers.forEach((lineNumber, index) => {
const lineContent = affectedLineContent[index]
const numLeadingSpaces = lineContent.search(/\S/)
const tsIgnoreContent = `${' '.repeat(numLeadingSpaces)}// @ts-ignore`
fileContent.splice(index + lineNumber - 1, 0, tsIgnoreContent)
})
await writeFile(filename, fileContent.join('\n'), { encoding: 'utf-8' })
}
}
main()
@jorgeborges
Copy link

Thanks for this!

@sanderdrummer
Copy link

Thanks, this is genius ❤️

@ALEUT
Copy link

ALEUT commented Dec 15, 2023

Thanks, it helped a lot, suggestion to fix: if > 1 error on the line, it adds several // @ts-ignore like

      // @ts-ignore
      // @ts-ignore
      // @ts-ignore
      adminApi.authDeleteOrgMiddleware(req, res, next);

@gvannest
Copy link

Awesome ! It saved me 3 days of boring work ^^ 🙏

@tim-prom
Copy link

Thanks, it helped a lot, suggestion to fix: if > 1 error on the line, it adds several // @ts-ignore like

      // @ts-ignore
      // @ts-ignore
      // @ts-ignore
      adminApi.authDeleteOrgMiddleware(req, res, next);

This can be fixed by changing line 31 to remove duplicates:

const lineNumbers = [...new Set(files[filename])]

@zorji
Copy link
Author

zorji commented Jul 26, 2024

Updated. Thx for the suggestion @gvannest @tim-prom

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