Tips on retrieving the abstract syntax tree (AST) from specific Typescript code using the freely available Typescript compiler source code

Typescript is now fully open source and can be found at Tyescript. I am developing an application that takes Typescript code as input and outputs the AST (Abstract Syntax Tree) of the given code. Can you suggest a method to extract the AST of Typescript code input without compiling it and converting it into Javascript?

Answer №1

Basic example:

const fileNames = ["C:\\MyFile.ts"];
const compilerOptions: ts.CompilerOptions = {
    // specify compiler options here if needed...
    // refer to ts.CompilerOptions for available settings
};
const program = ts.createProgram(fileNames, compilerOptions);
const typeChecker = program.getTypeChecker();
const sourceFiles = program.getSourceFiles();

sourceFiles.filter(f => /MyFile\.ts$/.test(f.fileName)).forEach(sourceFile => {
    ts.forEachChild(sourceFile, node => {
        const declaration = node as ts.Declaration;
        if (declaration.name) {
            console.log(declaration.name.getText());
        }
    });
});

For instance, providing it with a C:\MyFile.ts that contains:

class MyClass {}
interface MyInterface {}

The output would be MyClass and MyInterface.

Exploring beyond this demonstration requires significant effort. You may find it more helpful to explore or contribute to this ongoing project.

Answer №2

Although the TypeScript compiler does not directly support it, you can achieve this by using recast and babylon@next libraries. However, it is important to rely on the syntax defined by these technologies for representing TypeScript code AST and ensure that they stay up-to-date with the frequent new language features introduced in TypeScript releases. Unlike languages like JavaScript which have well-defined versions and standard releases, TypeScript evolves rapidly with short periods between updates. Therefore, if your users start utilizing new language features, it is crucial for these technologies (especially babylon) to remain current:

// npm install recast babylon@next
const source = `
interface I {
  color: string
}
class C implements I{
  color: string='blue'
}
`
const recast = require('recast')
const tsParser = require("recast/parsers/typescript")
const ast = recast.parse(source, {
  parser: tsParser
});
console.log(`
CODE: 

${source}

AST: 

${JSON.stringify(ast)}
`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to leverage Composite API in place of Mixin or Extends functionality

Currently, I am exploring the use of Vue3 for my project. One issue I am facing is that I need to create multiple components (SFC) with similar properties. I want to define these common properties using the composite API across all components, like so: con ...

AngularFire2 Firestore Custom Query: retrieve documents based on current date and time.startTime

Welcome to the world of AngularFire2 and Firestore! My objective is clear: Query data from Firestore where startTime matches currentDateRange. I am facing some challenges with creating a dynamic query in Firestore. After going through the official docume ...

How to Align Printed Output in Angular Components

I am a beginner in Angular and I am looking to display modal information. To print the data, I am using onclick=print(). The data shows up in the print preview, but it is not aligned correctly. Here is a screenshot of my page. I want to align the data prop ...

Using a method call instead of a property for the ngFor directive can lead to an infinite loop of loading

Within my template, I have included the following code: <a *ngFor="let item of navItems" [routerLink]="item.link" routerLinkActive="active" class="navigation-item" [ngClass]="{'enabled': item.enabled}" > <span class="color ...

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

Revamping elements according to ordered array. Angular version 4.3

Dealing with an array of data that needs to be sorted for displaying in a component seems to be a challenge. Despite having a functional code sample demonstrating the concept, the sorting is not reflected in the Angular app's DOM. The original data i ...

Tips for resolving the error message "Cannot use type '{}' as an index type"

interface TicketTime { startTime: string; endTime: string; } interface TicketInfo { id: number; from: string; to: string; company: string; price: number; time: TicketTime; duration: number; connectionAmount: numb ...

The TypeScript declarations for Forge Viewer do not include typings related to Profiles

I've been utilizing typescript definitions for Forge from the DefinitelyTyped repository: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-viewer However, there seems to be a lack of typings, particularly those associated wi ...

Using Typescript in the package.json as a dependency

After initiating a React project with typescript using the command below: npx create-react-app frontend --template typescript https://i.sstatic.net/8n4O5.png I noticed that the tyepscript, @testing, and @types libraries were added to dependencies rather ...

The TypeScript compiler does not recognize the property 'theme' in this context

I am currently working on a ReactJS starter project using typescript along with material-ui v1.x beta. I have encountered an issue with the themes, which are detailed at: . TypeScript is throwing errors stating that the 'theme' property does not ...

Angular CDK Overlay allows for bringing multiple overlays to the front effectively

Currently, I am experiencing an issue with Angular 15 where a click event placed within a mousedown event does not trigger. Interestingly, if the position of the element is not changed using appendChild, both the mousedown and click events work as expected ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Steps for confirming a property setting on an interface

I am working with the following interface export interface Command { id: CommandId; disabled: boolean; } My goal is to verify that the 'disabled' property has been changed. Here are my attempts: 1) Creating an object and checking if t ...

Guide on accessing the value within an array located inside an object

Hello everyone, I'm new to Angular and I need some help accessing the values inside objects. Specifically, I'm trying to access the SuccessCount in this Array. Here is my attempt: goodResponse=[ {compId: 1, companyName: "A", pendingCount: 0 ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

Navigating between pages has become challenging due to issues with the navbar, sidebar,

I successfully developed 4 Angular components: 1st component: menu 2nd component: header 3rd component: home 4th component: login The menu component features a sidebar/navbar created using Material UI. The login component consists of the login page. Howe ...

Dynamically generating an Angular component and populating it with data

I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following: PARENT COMPONENT Within the .ts file: @ViewChild(InjectDirective) injectComp: InjectDirect ...

Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present? type Foo = {}; class Bar<P extends Foo> { static make<P extends Foo>(a?: P): Bar<P> { return new Bar(); } } Bar.make() // returns Bar<Foo> ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...