TypeScript API type checking on modified source file

449 views Asked by At

Desired Solution

I am looking for the most efficient way to do type checking on a SourceFile's modified AST.

Undesired Solution

I do not want to serialize/emit the modified SourceFile's AST to text and then parse the text back into a new SourceFile.


I am aware of the BuilderProgram that can be used to incrementally build a Program [1]. However, I have not seen any way of updating a SourceFile other than working with text range changes. It seems to be very resource-consuming since I already have the actual modified AST ready.

Compiler API docs

https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API


[1] https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#writing-an-incremental-program-watcher

1

There are 1 answers

0
David Sherret On BEST ANSWER

See my answer here.

The TypeScript compiler was not designed for that scenario. Type checking happens before transformation and so the type checker often assumes the source file text is in sync with the AST. This may change going forward, but it is the current state of things.

So in order for the code to be reliable, you must get the corresponding source file text for the current state of the AST. The easiest way is unfortunately your undesired solution of printing out the final state of the AST with the printer (ts.createPrinter) and then reparsing the source file.