TypeScript Parser for AST Generation
The `typescript-parser` package provides a utility for parsing TypeScript and JavaScript files to generate a 'human-readable' Abstract Syntax Tree (AST). It leverages the official TypeScript compiler's parsing capabilities internally. The current stable version is 2.6.1, released in August 2018. Due to the lack of activity since then, its release cadence is effectively halted. Its key differentiator lies in its promise of a more accessible AST representation compared to the raw TypeScript compiler AST, aiming to simplify consumption for tools that need to analyze code structure, such as IDE extensions or code generators. It primarily operates by parsing either source code strings or file paths, and can also build a declaration index for multiple files.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'length')
cause This error was reported in older versions due to an issue with the parser when encountering specific TypeScript constructs, especially with malformed or unexpected input.fixUpdate to at least `v2.4.0` where a fix for 'typescript error that reads length of undefined' was applied. Ensure input source code is valid TypeScript/JavaScript syntax. -
Error: Cannot find module 'typescript-parser'
cause The `typescript-parser` package was not found in `node_modules`, likely due to incorrect installation or usage in an environment where dependencies are not properly resolved.fixRun `npm install typescript-parser` or `yarn add typescript-parser` in your project directory. Ensure your `node_modules` are accessible and environment variables like `NODE_PATH` are correctly configured if not using standard resolution.
Warnings
- gotcha The package has not been updated since August 2018. This means it may not correctly parse newer TypeScript syntax features (e.g., optional chaining, nullish coalescing, private class fields, import assertions) introduced in TypeScript versions 3.x, 4.x, or 5.x.
- gotcha Performance for very large files or projects might be a concern. The library's internal parsing mechanism (recursive vs. iterative BTree Walker) has seen changes in minor versions, which could affect performance characteristics, especially in older versions.
Install
-
npm install typescript-parser -
yarn add typescript-parser -
pnpm add typescript-parser
Imports
- TypescriptParser
const TypescriptParser = require('typescript-parser').TypescriptParser;import { TypescriptParser } from 'typescript-parser'; - AST declarations (e.g., ClassDeclaration)
import { ClassDeclaration, PropertyDeclaration } from 'typescript-parser';
Quickstart
import { TypescriptParser } from 'typescript-parser';
async function parseCode() {
const parser = new TypescriptParser();
const sourceCode = `
interface MyInterface {
id: string;
name?: string;
}
export class MyClass implements MyInterface {
private _id: string;
public name: string;
constructor(id: string, name: string) {
this._id = id;
this.name = name;
}
public get id(): string {
return this._id;
}
public greet(): string {
return `Hello, ${this.name}!`;
}
}
`;
try {
const parsed = await parser.parseSource(sourceCode);
console.log('Parsed declarations:', parsed.declarations.map(d => d.name));
// Example: Find the class declaration
const myClass = parsed.declarations.find(d => d.name === 'MyClass');
if (myClass && 'members' in myClass) {
console.log('MyClass members:', myClass.members.map((m: any) => m.name));
}
} catch (error) {
console.error('Error parsing source:', error);
}
}
parseCode();