Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find kind of TypeReference using TypeScript API

I'm trying to find the kind (class, interface, type alias, enumeration ...) of a TypeReference.

I have this:

const anode = node as ts.TypeReferenceNode;
const symbol = this.typechecker.getSymbolAtLocation(anode.typeName) as ts.Symbol;
const type = this.typechecker.getTypeOfSymbolAtLocation(symbol, anode);
const decls = symbol.getDeclarations() as ts.Declaration[]; 

But the call to getSymbolAtLocation returns undefined.

anode is a TypeReferenceNode (kind 159) according to VSC debugger:

enter image description here

And escapedText ETypes references to an enum reference.

like image 669
lilezek Avatar asked Mar 13 '26 00:03

lilezek


1 Answers

I found out a solution:

const anode = node as ts.TypeReferenceNode;
const type = this.typechecker.getTypeAtLocation(anode);
const symbol = type.symbol || type.aliasSymbol;
const decls = symbol.getDeclarations() as ts.Declaration[];

From the decls array you can find out whether the declarations are Interfaces, Classes, etc...

like image 170
lilezek Avatar answered Mar 15 '26 14:03

lilezek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!