Skip to content

ts.Declaration : how to get the actual declaration if same named variable is declared in 3 different files #29635

@abhijitparkhi1983

Description

@abhijitparkhi1983

TypeScript Version: 3.2.2

Search Terms:
ts.Declaration
getSymbolAtLocation

Description:

We have 3 .ts, A.ts, B.ts and C.ts.
All these files have a variable test declared inside them as global variable as follows:

var test : number = 100 ;
test  = 200;

Note: All the 3 files have same above code declared globally (outside any class or any structure.)
We are trying to use typescript compiler for getting the variable declaration and variable usage and we are trying to resolve the usage with the actual declaration.

For resolving the actual declaration for a variable getting used (like line 2 above in any of the 3 files), we use following code:

var options: ts.CompilerOptions = {
               noEmitOnError: true
               , strict: true
               , target: ts.ScriptTarget.Latest
               , module: ts.ModuleKind.CommonJS
               , skipLibCheck: true
               , experimentalDecorators: true
               , emitDecoratorMetadata : true
               , allowJs: true
               , noErrorTruncation : false
             };
       
           var compilerHost = ts.createCompilerHost(options);
           this.program = ts.createProgram(this.sourceFilesToParse, options, compilerHost);            
           this.typeChecker = this.program.getTypeChecker(); 
....
....
getDeclarationFromUsageNode(node: ts.Node) : ts.Declaration {
      var symbol = this.typeChecker.getSymbolAtLocation(node);
      if(symbol) {
         var declarations = symbol.getDeclarations();
         ....
     }
}

Expected behavior:
When we are trying to get the declaration of usage of test variable inside file A.ts at the second line (test = 200;), the above code should return only one declaration which is specific to A.ts file declared at first line (var test : number = 100 ;)

Actual behavior:
Now the problem with the above code is that declarations variable always has 3 entries in it (possibly because variable test has been declared in 3 files).

This is a kind of blocker. I am sure I am missing setting some configuration, some flag. It will be helpful if some one from the TS compiler team can help me with this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: APIRelates to the public API for TypeScriptQuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions