What is @typescript-eslint/visitor-keys?
The @typescript-eslint/visitor-keys package provides an enumeration of TypeScript ESTree AST node types and their respective visitor keys. It is primarily used in the context of ESLint plugins and custom rules development to traverse the AST (Abstract Syntax Tree) of TypeScript code and analyze or manipulate the code structure.
AST Node Traversal
This code demonstrates how to use the visitor keys from the package to traverse an AST node and its children recursively. The `traverseAST` function takes a node and a visitor object that contains methods corresponding to node types. It uses the visitor keys to determine which properties of a node to traverse.
const visitorKeys = require('@typescript-eslint/visitor-keys');
function traverseAST(node, visitor) {
if (visitor[node.type]) {
visitor[node.type](node);
}
const keys = visitorKeys[node.type] || [];
keys.forEach((key) => {
const value = node[key];
if (Array.isArray(value)) {
value.forEach(child => traverseAST(child, visitor));
} else if (value && typeof value === 'object') {
traverseAST(value, visitor);
}
});
}