Search code examples
javascripttypescriptvisual-studio-codeaureliatslint

Analyze a Typescript file to obtain class structure


I am trying to write a VS Code extension for Aurelia that will provide intellisense in the HTML file for properties and methods that are in its paired viewmodel typescript class.

I can get to the typescript file but I need a tool to analyze to extract the properties of the viewmodel class. Here is an example of such a class:

import { HttpClient } from 'aurelia-fetch-client';
import { observable, inject } from 'aurelia-framework';

@inject(HttpClient)
export class People {
    public people: Person[];
    @observable selectedPerson: Person;
    private httpClient: HttpClient
    public updateMessage: string;

    constructor(http: HttpClient) {
        this.httpClient = http;

        this.httpClient.fetch('http://localhost:5555/api/Persons?$top=10')
            .then(result => result.json() as Promise<ODataPerson>)
            .then(data => {
                this.people = data.value;
            });
    }

    setSelected(selected: Person) {
        this.selectedPerson = selected;
    }

    activate() {
    ...
    }
}

So I'd like to extract from this an array of the properties, i.e. people, selectedPerson, and updateMessage, and also if possible any public methods, i.e. setSelected.

The best way to do this would be to consume the class with a Require, and then use javascript reflection e.g.

var Reflector = function(obj) {
  this.getProperties = function() {
    var properties = [];
    for (var prop in obj) {
      if (typeof obj[prop] != 'function') {
        properties.push(prop);
      }
    }
    return properties;
  };

But to do this I'd have to compile the ts file down to Javascript and then I still couldn't consume it because to import and inject dependencies like HttpClient it needs to be running as part of the Aurelia application, whereas I am running from the context of a VS Code extension.

So I was looking at tools that might be able to analyse the code statically without consuming it, such as TSLint, but I can't see any facility to extract class properties and methods.

Does anyone know of any tools out there that could do what I'm trying to achieve?


Solution

  • You should use the compiler itself to achieve this. The compiler provides an API for intel sense that is used in all IDEs that support typescript. Link to the API. The language service should be able to analize the class and provide the information. I would look into weather you can't acces the Language service that is already running in VS Code, but I don't have info on that.