Search code examples
typescriptabstract-syntax-treetypescript-compiler-api

Get information from parent class when reading TypeScript files


I am successfully reading TS classes using ts.createProgram and program.getSourceFile. But when I am reading the class node to list the properties, it doesn't account the properties from the parent class. I can get the symbol and names of the extending classes from node.heritageClauses.

How can I also get the properties list of the parent classes?

ie:

// I can traverse the Refund class and find the *id* property along with its decorator.
export class Refund extends Model {
    @int({sys: 'codd'})
    public id?: number;
}

// How can I get information from the parent class Model?
export class Model {
  @bar()
  public foo: string;
}

Solution

  • In this case, you can get the type of the parent class by doing:

    const refundClassDecl = ...;
    const refundClassType = checker.getTypeAtLocation(refundClassDecl);
    
    const modelClassType = checker.getBaseTypes(refundClassType)[0];
    

    That won't work in every scenario though, as a base type could be for an interface, multiple interfaces, and optionally also have a class (ex. class MyClass extends Child implements SomeInterface, OtherInterface {}), or in some cases could be an intersection type if it's a mixin (ex. class MyClass extends Mixin(Base) {})... so you'll need to ensure the code handles those scenarios.

    All this said, you may just want to get the properties of the Refund class' type:

    const properties = refundClassType.getProperties();
    
    console.log(properties.map(p => p.name)); // ["id", "foo"]