typescript-compiler-api

TypeScript Checker Symbol Of "this"


I have this ts.Program/ts.SourceFile:

class MyClass {
   foo() {
      // @1
   }
}

Is there a way to obtain the symbol/type of the local this value at position @1? Unfortunately, this is not listed by checker.getSymbolsInScope. Ideally I would get the type of MyClass, so I could explore its members.

The solution should also work for these cases:

function foo(this: MyClass) {
  // @2
}

const obj = {
  bar() {
    // @3
  }
};

Thank you!


edit: This is the feature I needed this for:

Demo


Solution

  • There is an internal TypeChecker#tryGetThisTypeAt(nodeIn: ts.Node, includeGlobalThis = true): ts.Type method that will return this information. If you're ok with using internal API, then you can do:

    const type = (checker as any).tryGetThisTypeAt(nodeName) as ts.Type;
    

    To get the node's name, you'll need to traverse the tree to find the method or function declaration that is contained within the position, then the .name property will contain the node that you can provide to tryGetThisTypeAt.