dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
4.98k stars 195 forks source link

How to make tsquery works with ts-morph? #1368

Open jon9090 opened 1 year ago

jon9090 commented 1 year ago

Hi @dsherret maybe you can help me.

Since I upgrade ts-morph to the last version I get a typescript error and the integration with tsquery doesn't work.

Argument of type 'Node' is not assignable to parameter of type 'string | Node'.

I don't think the tsquery expect to node.compilerNode.

What can I do? Which property on ts-morph I can pass to tsquery to make it work?

https://codesandbox.io/s/elastic-chatterjee-j77h5j?file=/src/index.ts

import { tsquery } from "@phenomnomnominal/tsquery";
import { Project, Node, ClassDeclaration } from "ts-morph";

console.clear();

export const searchQuery = (node: Node, query: string) => {
  return tsquery(node.compilerNode as any, query).map(
    (n) => (node as any)._getNodeFromCompilerNode(n) as Node
  );
};

const project = new Project({});
project.createSourceFile(
  "foo.ts",
  `
 class Foo {
   init() {
    const foo = 1;
   }
 }

`
);
const fooClass = project
  .getSourceFile("foo.ts")
  ?.getClass("Foo") as ClassDeclaration;

const res = searchQuery(fooClass, 'Identifier[name="Animal"]');
console.log({ res });
mattvgm commented 1 year ago

I can confirm it's no longer working