Skip to content

Instantly share code, notes, and snippets.

@skovy
Last active Nov 1, 2022
Embed
What would you like to do?
Audit the number of `any` keywords and `@ts-expect-error` directives
import * as fs from 'fs';
import * as glob from 'glob';
import { parse } from '@babel/parser';
import traverse from '@babel/traverse';
export const isExpectErrorComment = (comment: string): boolean =>
comment.trim().startsWith('@ts-expect-error TS(');
let totalAnyKeywords = 0;
let totalExpectErrorDirectives = 0;
const processFileContents = (contents: string) => {
// Convert the file contents into an abstract syntax tree.
const ast = parse(contents, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
});
// Traverse the abstract syntax tree to find any
// instances of the `any` keyword.
traverse(ast, {
TSAnyKeyword() {
totalAnyKeywords += 1;
},
});
// The comments are already nicely parsed out.
ast.comments?.forEach((comment) => {
// Determine if the comment is a special comment
// that expects an error. Ignore it if not.
if (isExpectErrorComment(comment.value)) {
totalExpectErrorDirectives += 1;
}
});
};
// Find all the relevant file to audit.
const files = glob.sync('src/**/*.@(tsx|ts)');
files.forEach((file) => {
const contents = fs.readFileSync(file).toString();
processFileContents(contents);
});
console.log({ totalAnyKeywords, totalExpectErrorDirectives });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment