TypeScript Parser for AST Generation

2.6.1 · abandoned · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `TypescriptParser` and use it to parse a string of TypeScript source code, then log the names of the top-level declarations and members of a specific class found in the AST.

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();

view raw JSON →